C++结构体里面 string 类型赋值问题
#include<string>
using namespace std;
struct temp
{
string s;
};
int main()
{
const string p="aaa";
temp *q;
q=(struct temp*)malloc(sizeof(struct temp));
q->s=p;
}
上述那种情况的赋值会导致程序中断
需要用用 new 来分配内存,malloc 不会调用结构函数
结构体内的 string 不定长,不能动态分配内存。
#include<string>
using namespace std;
struct temp
{
string s;
};
int main()
{
const string p="aaa";
temp *q;
//q=(struct temp*)malloc(sizeof(struct temp));
q = new temp;
q->s=p;
C++的结构体和类都有默认构造函数的,不写都会自动实现一个。
malloc 只是分配内存。
new 除了分配内存还会调用构造函数的。