我正在尝试在我的类中创建一个静态字符串:(在我的头文件中)
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
我做错了什么?
您可以做的是在标头中声明字符串并在 .cpp 中初始化它。
在 MyClass.h 中
#include <string>
class MyClass
{
static std::string foo;
}
在MyClass.cpp中
#include "MyClass.h"
std::string MyClass::foo = "bar"
忽略特定的错误消息,核心问题是您试图在声明中初始化静态成员属性,而通常应该在定义中完成。
// 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];
};
如果该值是在变量的定义中定义的,则编译器只能在该单个翻译单元中使用它。看来您的编译器正在执行两项测试,一项用于常量测试,另一项用于 integral 部分,因此有两条错误消息。
另一件事可能会影响编译器中的设计,即 C++11 标准允许在类的非静态成员声明中使用初始化程序,然后将在每个不提供的构造函数的初始化程序列表中使用该初始化程序该字段的值:
struct test {
int a = 10;
int b = 5;
test() : a(5) // b(5) implicitly generated
{}
};
这与您的特定问题无关,因为您的成员是静态的,但它可能解释了为什么编译器中的测试按原样分开。
将声明与定义分开。在头文件中,执行以下操作:
static string description;
然后在一个翻译单元(一个 CPP 文件)中,执行以下操作:
string type::description = "foo";
我相信从 c++11 开始你可以使用
constexpr
class {
//...more code here
public: static constexpr float X = 1.2f;
}