为什么我不能在声明结构体时初始化它?

发布于 2024-12-26 02:55:08 字数 325 浏览 0 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

活泼老夫 2025-01-02 02:55:08

因为 C++ 不是这样工作的。

初始化器位于构造函数的初始化器列表中,例如

struct comp {
    long a;
    vector<int> b;
    bool c;

    comp() : b(9) { }
};

(请注意,这样定义的类不再是聚合。)

注意:C++11 添加了成员​​初始化器,但是仅使用复制初始化语法:

struct Foo {
    int a = 5;
    vector<char> b = vector<char>(8);
};

编译器对此的支持仍然不完整。

Because C++ doesn't work like that.

Initializers go in the initializer list of a constructor, e.g.

struct comp {
    long a;
    vector<int> b;
    bool c;

    comp() : b(9) { }
};

(Note that a class thus defined is no longer an aggregate.)

Note: C++11 adds member initializers, but only using copy-initialization syntax:

struct Foo {
    int a = 5;
    vector<char> b = vector<char>(8);
};

Compiler support for this is still incomplete.

未央 2025-01-02 02:55:08

向量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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文