[英]How To Declare Static Const Array
我用公共修饰符在 class 中这样编码:
static const string brands[] = {"Coca-Cola","Pepsi","Ruffles"};
它给了我这个错误代码:
E1591
我该如何解决?
据我所知,您的static const std::string []
不能拥有类内初始化程序。
您应该在 class 声明之外对其进行初始化。 例如:
#include <string>
class Foo
{
public:
static const std::string brands[];
};
// in your Foo.cpp file
const std::string Foo::brands[] = {"Coca-Cola","Pepsi","Ruffles"};
The C++ answer is to skip using C arrays, which have limitations in C++ not present in C, and instead use std::vector
:
static const std::vector<std::string> brands = {"Coca-Cola","Pepsi","Ruffles"};
请注意,由于各种原因,应该作为
using namespace std
出现的std::
前缀可能会产生很大的问题,最重要的是名称冲突。 前缀的存在是有原因的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.