【问题标题】:How To Declare Static Const Array如何声明静态常量数组
【发布时间】:2021-01-16 12:37:19
【问题描述】:

我在课堂上用 public 修饰符这样编码:

    static const string brands[] = {"Coca-Cola","Pepsi","Ruffles"};

它给了我这个错误代码:

E1591

我该如何解决?

【问题讨论】:

  • 请包含完整错误文本。不是每个人都通过数字知道随机编译器错误代码。

标签: c++ arrays static


【解决方案1】:

据我所知,您的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 起)
  • @Sprite:是的,这对于 C++17 来说很好,没有警告。在我的 Ubuntu 18 上使用 C++14,它会产生一个警告 (warning: inline variables are only available with -std=c++1z or -std=gnu++1z),但我仍然可以编译它。
【解决方案2】:

C++ 的答案是跳过使用 C 数组,它在 C++ 中存在限制,而在 C 中不存在,而是使用 std::vector

static const std::vector<std::string> brands = {"Coca-Cola","Pepsi","Ruffles"};

注意std:: 前缀应该以using namespace std 出现,这可能由于各种原因造成严重问题,最重要的是名称冲突。前缀的存在是有原因的。

【讨论】:

  • @Raildex 意见问题。除非std::vector 引起问题,否则通常没问题。我见过std::array 是必要的案例数量非常少。如果这是一个问题,它可能会更有效。
猜你喜欢
  • 1970-01-01
  • 2022-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-15
  • 1970-01-01
相关资源
最近更新 更多