【发布时间】:2021-01-16 12:37:19
【问题描述】:
我在课堂上用 public 修饰符这样编码:
static const string brands[] = {"Coca-Cola","Pepsi","Ruffles"};
它给了我这个错误代码:
E1591
我该如何解决?
【问题讨论】:
-
请包含完整错误文本。不是每个人都通过数字知道随机编译器错误代码。
我在课堂上用 public 修饰符这样编码:
static const string brands[] = {"Coca-Cola","Pepsi","Ruffles"};
它给了我这个错误代码:
E1591
我该如何解决?
【问题讨论】:
据我所知,您的static const std::string [] 不能使用类内初始化程序。
您应该在类声明之外对其进行初始化。 例如:
#include <string>
class Foo
{
public:
static const std::string brands[];
};
// in your Foo.cpp file
const std::string Foo::brands[] = {"Coca-Cola","Pepsi","Ruffles"};
【讨论】:
static inline const string brands[] = {"Coca-Cola","Pepsi","Ruffles"}; 在类声明中也可以。 (C++17 起)
warning: inline variables are only available with -std=c++1z or -std=gnu++1z),但我仍然可以编译它。
C++ 的答案是跳过使用 C 数组,它在 C++ 中存在限制,而在 C 中不存在,而是使用 std::vector:
static const std::vector<std::string> brands = {"Coca-Cola","Pepsi","Ruffles"};
注意
std::前缀应该以using namespace std出现,这可能由于各种原因造成严重问题,最重要的是名称冲突。前缀的存在是有原因的。
【讨论】:
std::vector 引起问题,否则通常没问题。我见过std::array 是必要的案例数量非常少。如果这是一个问题,它可能会更有效。