关键词
聚合初始化
结构体带string
string异常代码
#include <windows.h>
#include <iostream>
using namespace std;
typedef struct {
string str;
} test;
int main() {
int a = 1;
test test1 = {0};
string test2(0);
test test3 = {};
return 1;
}
如图{0}初始化等同于string(0);
string正常的代码
#include <windows.h>
#include <iostream>
using namespace std;
typedef struct {
int c; //接收0
string str;
} test;
int main() {
int a = 1;
test test1 = {0};
// string test2(0);
test test3 = {};
return 1;
}
memset初始化结构体内对象
memset异常代码
#include <windows.h>
#include <iostream>
using namespace std;
typedef struct {
string str;
} test;
int main() {
int a = 1;
test test1;
memset(&test1, 0, sizeof(test)); //注释掉即可正常
test1.str = "123";
printf("test1.str %s \n", test1.str.c_str());
return 1;
}
总结
- 第一个如果是对象必须可通过单参数0构造
- string不能通过0构造
- 不用memset设置带非基本数据类型的结构体
思考
万事不能靠表面,可从底层去思考解决