2
3
4
5
6
7
8
9
10
11
12
13
14
#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除了分配内存还会调用构造函数的。