c++程序,今日使用再平常不过的初始化列表,居然报错
struct sales {
char bookNo;
unsigned units_sold = 0;
double revenue = 0.0;
};
int main() {
sales a = {0};
// print(cout, a);
}
错误信息
cpp_primer.cc:62:17: error: could not convert '{0}' from '' to 'sales'
62 | sales a = {0};
| ^
| |
|
问题是在结构体内定义初值了,此时初始化列表不能用
将结构体改为
struct sales {
char bookNo;
unsigned units_sold;
double revenue;
};
就可以了
总结两种初始化方式:
- 结构体定义时给定初值
- 初始化列表赋值
以上两种方式互斥,只能选择一种使用
参考资料 https://qa.1r1g.com/sf/ask/2644377641/



