【问题标题】:std::vector with size and value constructor fails to compile under MSVC 16.9具有大小和值构造函数的 std::vector 无法在 MSVC 16.9 下编译
【发布时间】:2021-03-04 04:22:06
【问题描述】:

这是我在使用 std::vector 和 MSVC 时遇到的问题的最小可重现示例

#include <iostream>
#include <vector>
#include <string>

using namespace std;    // For brevity

struct Struct
{
    vector< int > Values(6, 0);         // Should hold 6 zeros
    vector< int > NormalConstructor;    // Example of normal vector

    void Dump() { for (auto val : Values) { cout << val << " "; } }
};

int main()
{
    Struct s;

    s.Dump();

    cout << "\n";
}

vector&lt; int &gt; Values(6, 0); 行的结果是error C2059: syntax error : 'constant',名为Value 的变量被着色,就好像它是一个函数声明一样。

cppreference.com 说这个构造函数 “3) 构造具有值 value 元素的 count 个副本的容器”

这里有几个问题,我看过这些问题,但似乎没有一个表明出了什么问题,或者我应该做些什么来避免这个错误。

我应该怎么做?

【问题讨论】:

    标签: c++ visual-studio stdvector


    【解决方案1】:

    括号初始值设定项不能用于初始化默认成员初始值设定项中的数据成员(C++11 起)。 (编译器试图将其解释为函数声明。)

    您可以改用 euqal-sign 初始化程序。

    struct Struct
    {
        vector< int > Values = vector< int >(6, 0);  // Should hold 6 zeros
        vector< int > NormalConstructor;             // Example of normal vector
    
        void Dump() { for (auto val : Values) { cout << val << " "; } }
    };
    

    或者在构造函数中使用成员初始化列表。

    struct Struct
    {
        vector< int > Values;
        vector< int > NormalConstructor;             
    
        void Dump() { for (auto val : Values) { cout << val << " "; } }
    
        Struct() : Values(6, 0) {}
    };
    

    【讨论】:

    • 不根据 cppreference.com。这是他们矢量构造函数页面中的一个示例。 // words4 是 {"Mo", "Mo", "Mo", "Mo", "Mo"} std::vector<:string> words4(5, "Mo"); . .当我点击他们的“运行此代码”按钮时,这正是我得到的......
    • 抱歉,我想补充一点,我不是在尝试初始化数据成员,而是在尝试调用它的构造函数。
    • @GeoffreyArmstrong 正如我在答案中解释的那样,语法不能用于结构/类的数据成员。
    • 哦,我明白了,不能在课堂上这样做......我会检查一下。谢谢。
    • 这是 100% 正确的。从您的示例中添加该分配有效。谢谢!
    猜你喜欢
    • 2013-06-07
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    • 2017-08-11
    • 2013-12-08
    • 1970-01-01
    • 2012-11-03
    • 1970-01-01
    相关资源
    最近更新 更多