使用new来创建结构体

如下代码:
#include <iostream>

struct MyStruct {
    char name[20];
    float volume;
    double price;
};

using namespace std;
int main(int argc, const char * argv[]) {

    MyStruct *ms =  new MyStruct;
    cout << "Enter the name of struct :" << endl;
    cin.get(ms->name,20);

    cout << "Enter the volume in cubic feet:" << endl;
    cin >>  ms->volume;

    cout << "Enter the price : " << endl;
    cin >> (*ms).price;

    delete ms;
    return 0;
}

输出结果:
Enter the name of struct :
py
Enter the volume in cubic feet:
10.23
Enter the price : 
9.22
Program ended with exit code: 0
1.使用new来创建结构体指针,注意new和delete的配对使用
MyStruct *ms =  new MyStruct;

delete ms;
2.访问结构体成员
ms->volume;

(*ms).price;
什么时候使用句点运算,什么时候使用-->箭头运算?

如果结构体标识是结构名称,则使用句点运算;如果标识是指向结构体的指针对象,则使用-->箭头运算符。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容