为什么我不能在声明结构体时初始化它?
struct comp {
long a;
vector<int> b(9);
bool c;
};
错误:
code.cpp:67:19: error: expected identifier before numeric constant
code.cpp:67:19: error: expected ‘,’ or ‘...’ before numeric constant
这有什么问题吗?如果我说 b
将有 9 个元素,为什么 g++ 不接受?
struct comp {
long a;
vector<int> b(9);
bool c;
};
Errors:
code.cpp:67:19: error: expected identifier before numeric constant
code.cpp:67:19: error: expected ‘,’ or ‘...’ before numeric constant
What is wrong with this? Why doesn't g++ accept if I say that b
will have 9 elements?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因为 C++ 不是这样工作的。
初始化器位于构造函数的初始化器列表中,例如
(请注意,这样定义的类不再是聚合。)
注意:C++11 添加了成员初始化器,但是仅使用复制初始化语法:
编译器对此的支持仍然不完整。
Because C++ doesn't work like that.
Initializers go in the initializer list of a constructor, e.g.
(Note that a class thus defined is no longer an aggregate.)
Note: C++11 adds member initializers, but only using copy-initialization syntax:
Compiler support for this is still incomplete.
向量b(9);
是一个具体的数据结构。它正在寻找类型和标签,而不是实际的数据结构。向量b;
应该就是您所需要的。vector<int> b(9);
is a concrete data structure. It's looking for a type and label, not an actual data structure.vector<int> b;
should be all you need.