C++具有类内初始化程序的成员必须是const

Chi*_*hin 21 c++ visual-studio-2010

我正在尝试在我的类中创建一个静态字符串:(在我的头文件中)

static string description = "foo";
Run Code Online (Sandbox Code Playgroud)

但我收到这个错误:

IntelliSense: a member with an in-class initializer must be const
Run Code Online (Sandbox Code Playgroud)

如果我改成它:

static const string description = "foo";
Run Code Online (Sandbox Code Playgroud)

我得到了这个错误:

IntelliSense: a member of type "const std::string" cannot have an in-class initializer
Run Code Online (Sandbox Code Playgroud)

我做错了什么?

Kev*_*ARD 20

你可以做的是在标题中声明字符串并在.cpp中初始化它.

在MyClass.h中

#include <string>
class MyClass
{
  static std::string foo;
}
Run Code Online (Sandbox Code Playgroud)

在MyClass.cpp中

#include "MyClass.h"
std::string MyClass::foo = "bar"
Run Code Online (Sandbox Code Playgroud)

  • 任何整洁的选择? (2认同)

Dav*_*eas 5

忽略特定错误消息的核心问题是您尝试在声明中初始化静态成员属性,而通常应该在定义中完成.

// header
struct test {
  static std::string x;
};
// single cpp
std::string test::x = "foo";
Run Code Online (Sandbox Code Playgroud)

现在回到错误消息.C++ 03标准中有一个例外,它允许为常量整数类型的声明提供初始化器,以便该值可以在包含头的所有转换单元中可见,因此可以用作常量表达式:

// header
struct test {
   static const int size = 10;
};
// some translation unit can do
struct A {
   int array[test::size];
};
Run Code Online (Sandbox Code Playgroud)

如果值是在变量的定义中定义的,那么编译器只能在该单个转换单元中使用它.您的编译器似乎正在进行两个测试,一个用于const-ness,另一个用于整数部分,因此有两个错误消息.

在编译器中可能影响该设计的另一件事是C++ 11标准允许在类的非静态成员的声明中使用初始化器,然后将在每个不提供的构造函数的初始化器列表中使用该初始化器.该字段的值:

struct test {
   int a = 10;
   int b = 5;
   test() : a(5) // b(5) implicitly generated
   {} 
};
Run Code Online (Sandbox Code Playgroud)

这与您的特定问题无关,因为您的成员是静态的,但它可能解释了为什么编译器中的测试按原样进行拆分.