C++基本语法-----struct

来源:互联网 发布:hat linux重置root密码 编辑:程序博客网 时间:2024/06/02 06:50

struct

example

typedef struct MyType{    int first;    int second;    string s;    MyType()    {        first = 1;        s = "asdfgh";    }    ~MyType()    {        cout << "I was destroyed!";    }}MyType;

可以在结构体中声明int、double等数据类型,MyType()相当于构造函数,即默认该结构体中的各成员变量的值,~MyType()是析构函数,在释放此内存空间时会执行该函数

example中遇到的问题

  • string类型的数据无法用cout直接输出

    会报the error: no operator << matches these operands的错误,直接在头文件中增加#include<string>即可,

    参考链接:http://blog.csdn.net/chenshaoxunhuan/article/details/8289449

  • delete 结构体时会卡住

    释放内存的时候会根据初始化时的数据类型的大小来释放相应的内存空间,对于int、double等已有的数据类型,释放时也会释放相应的大小,而对于自定义的结构体,则需要根据new时的大小来判断其释放的内存空间的大小。

    参考链接:http://blog.csdn.net/love_gaohz/article/details/9664483

完整的代码如下

下面的代码因为是用new来初始化MyType,因此delete时不会卡死
#include
#include

using namespace std;int main(){    typedef struct MyType{        int first;        int second;        string s;        MyType()        {            first = 1;            s = "asdfgh";        }        ~MyType()        {            cout << "I was destroyed!";        }    }MyType;    int x = 0;    int y = 0;    MyType *m = new MyType;    cout << m->first << "  " << m->s;    cout << m->s;    delete m;    cout << endl;    while (!getchar());    return 0;}
0 0
原创粉丝点击