我看不出以下(非常人为的)代码有什么问题。这可能是我在 mystruct
中声明大小为 2 的 vector 的方式。但这不是我们声明一个大小为 2 的 vector 的方式吗?其内容尚未初始化?
struct mystruct
{
int a;
int b;
vector<double> c(2); };
int main(int argc, char *argv[])
{
mystruct test;
(test.c)[0]=3.4;
(test.c)[1]=1.8;
return 0; }
编译器向我抛出以下错误消息:
g++ -Wall simple.cpp
simple.cpp:18: 错误:数字常量之前需要标识符
simple.cpp:18: 错误:数字常量前需要‘,’或‘...’
simple.cpp: 在函数‘int main(int, char**)’中:
simple.cpp:32: 错误:数组的无效类型‘[int]’ 下标
simple.cpp:33: 错误:数组下标的无效类型‘[int]’
最佳答案
您不能在类定义中初始化 mystruct::c
,这必须在构造函数中完成。
struct mystruct {
mystruct() : c(2) { }
vector<double> c;
};
关于声明结构时的 C++ 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7489282/