gpt4 book ai didi

c++ - 如何在C++ 11中的类中声明n个字符串的 vector

转载 作者:行者123 更新时间:2023-12-03 07:22:29 25 4
gpt4 key购买 nike

class abc
{
public:
std::vector<std::string> other_license_files(30);
};
这应该声明一个由30个元素组成的 vector ,每个元素为一个空字符串。但是我得到了错误
数值常量前应为','或'...'。
尽管在第98页中,C++入门并未提及在类中使用它。假设从函数来看这是可以的。我不知道这些信息可能在哪里。

最佳答案

您遇到的是Most Vexing Parse!
简短的答案是,编译器认为您正在声明一个返回std::vector<std::string>而不是成员变量的成员函数。
典型的解决方案是使用构造函数并在其中传递参数。但是,由于您使用的是C++ 11,因此可以使用花括号。 Here's an example:

#include <vector> // std::vector
#include <string> // std::string

class foo {
public:
// error: expected identifier before numeric constant
// std::vector<std::string> bad_member_(30);

// OK!
std::vector<std::string> member_{30};
};


auto bar() {
foo f;
return f.member_.size();
}

关于c++ - 如何在C++ 11中的类中声明n个字符串的 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64702526/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com