如何声明静态常量数组
How To Declare Static Const Array
我在 class 中用 public 修饰符这样编码:
static const string brands[] = {"Coca-Cola","Pepsi","Ruffles"};
它给了我这个错误代码:
E1591
我该如何解决?
C++ 的答案是跳过使用 C 数组,它在 C++ 中有限制,但在 C 中不存在,而是使用 std::vector
:
static const std::vector<std::string> brands = {"Coca-Cola","Pepsi","Ruffles"};
Note the std::
prefix which should be present as using namespace std
can be highly problematic for a variety of reasons, most of all name conflict. The prefix exists for a reason.
据我所知,您的 static const std::string []
.
不能有 in-class 初始值设定项
您应该在 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"};
我在 class 中用 public 修饰符这样编码:
static const string brands[] = {"Coca-Cola","Pepsi","Ruffles"};
它给了我这个错误代码:
E1591
我该如何解决?
C++ 的答案是跳过使用 C 数组,它在 C++ 中有限制,但在 C 中不存在,而是使用 std::vector
:
static const std::vector<std::string> brands = {"Coca-Cola","Pepsi","Ruffles"};
Note the
std::
prefix which should be present asusing namespace std
can be highly problematic for a variety of reasons, most of all name conflict. The prefix exists for a reason.
据我所知,您的 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"};