C++ C++;具有类内初始值设定项的成员必须是常量

C++ C++;具有类内初始值设定项的成员必须是常量,c++,visual-studio-2010,C++,Visual Studio 2010,我试图在我的类中创建一个静态字符串:(在我的头文件中) 但我得到了一个错误: IntelliSense: a member with an in-class initializer must be const 如果我将其更改为: static const string description = "foo"; 我得到了这个错误: IntelliSense: a member of type "const std::string" cannot have an in-class initial

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

但我得到了一个错误:

IntelliSense: a member with an in-class initializer must be const
如果我将其更改为:

static const string description = "foo";
我得到了这个错误:

IntelliSense: a member of type "const std::string" cannot have an in-class initializer

我做错了什么?

您可以在标题中声明字符串并在.cpp中初始化它

在我的班级里

#include <string>
class MyClass
{
  static std::string foo;
}

将声明与定义分开。在头文件中,执行以下操作:

static string description;
string type::description = "foo";
然后在一个翻译单元(一个CPP文件)中执行以下操作:

static string description;
string type::description = "foo";

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

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

// header
struct test {
   static const int size = 10;
};
// some translation unit can do
struct A {
   int array[test::size];
};
如果该值是在变量的定义中定义的,那么编译器只能在单个转换单元中使用它。您的编译器似乎正在执行两个测试,一个是常量测试,另一个是整型部分测试,因此有两条错误消息

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

struct test {
   int a = 10;
   int b = 5;
   test() : a(5) // b(5) implicitly generated
   {} 
};

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

我不知道静态成员和常量成员之间到底需要什么。静态成员将与类本身相关联,而不是与实例相关联,常量成员将与实例相关联,并且将是常量

但是,这可能与


关于

使用description var时粘贴代码什么是只包含头的库?@ShitalShah:如果你有一个C++17编译器(gcc刚刚问世),你可以使用一个内联变量,但对于所有版本都适用的简单答案是,你将变量推送到一个局部静态变量:
struct{static const std::string&x(){static std::string x=“foo”;return x;};
有更整洁的选项吗?
struct test {
   int a = 10;
   int b = 5;
   test() : a(5) // b(5) implicitly generated
   {} 
};