我正在尝试在我的类中创建一个静态字符串:(在我的头文件中)
static string description = "foo";但是我得到了这个错误:
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我做错什么了?
发布于 2012-11-08 01:25:34
您可以做的是在头部中声明字符串,并在.cpp中对其进行初始化。
在MyClass.h中
#include <string>
class MyClass
{
static std::string foo;
}在MyClass.cpp中
#include "MyClass.h"
std::string MyClass::foo = "bar"发布于 2012-11-08 01:28:24
忽略具体的错误消息,核心问题是您试图在声明中初始化静态成员属性,而通常应该在定义中完成此操作。
// header
struct test {
static std::string x;
};
// single cpp
std::string test::x = "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
{}
};这与您的特定问题无关,因为您的成员是静态的,但这可能解释了为什么编译器中的测试按原样拆分。
发布于 2012-11-08 01:27:47
将声明与定义分开。在头文件中,执行以下操作:
static string description;然后在恰好一个翻译单元(一个CPP文件)中,执行以下操作:
string type::description = "foo";https://stackoverflow.com/questions/13274876
复制相似问题