字符串上的C++静态属性初始化错误
#include <iostream>
#include <cstring>
#include <QString>
using namespace std;
class A {
public:
static const int i = 9;
static const int PI = 1.3;
static const char ch = 's';
static const string str = "hello world"; // <--- error
static const QString str2 = "hello world"; // <--- error
};
int main(int argc, char **argv) {
cout << "Hello world" << endl;
return 0 ;
}
由于代码提供了一切,我如何初始化字符串。字符串上的C++静态属性初始化错误
非整体式部件(其包括string
和您的用户定义的类型),所需要的类定义外部被初始化,在单个实施文件(.cc
或.cpp
通常)。
在你的情况,因为你没有在头类定义分开,您可以在课后正确初始化static
S:
class A {
public:
static const int i = 9;
static const int PI = 1.3;
static const char ch = 's';
static const string str;
static const QString str2;
};
const string A::str = "hello world";
const QString A::str2 = "hello world";
编辑:除此之外,作为纳瓦兹指出的那样,定义string
的头文件是<string>
,而不是<cstring>
。
这不是“用户定义的成员”。在C++ 03中,它是“非整型类型”,在C++ 11中,它没有任何常量表达式初始化。 – 2012-03-24 12:57:42
@KerrekSB:实际上,只有* static const整数和枚举*可以在C++ 03中进行类内初始化。 – 2012-03-24 13:02:02
@Als为什么'char'为他工作? – 2012-03-24 13:02:32
-
第一件事第一件事。您尚未包含
<string>
。所以,这样做第一:#include <string>
std::string
在<string>
定义,而不是在<cstring>
正如你可能想象。 之后,在C++ 03中,类的非整型静态成员的初始化必须在类之外。
在C++ 11中,如果只包含
<string>
,代码将会被编译。无需在课堂外定义静态成员。
该问题已经回答,但只是在下一次:说出什么错误得到确切。 – 2012-03-24 12:54:14
@MrLister现在工作正常。但是我想知道const如何在以后被宣布! – Dewsworld 2012-03-24 13:09:49