Dew*_*rld 1 c++ qt static-methods class
#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 ;
}
Run Code Online (Sandbox Code Playgroud)
由于代码提供了所有内容,我如何初始化字符串.
非整数类型成员(包括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";
Run Code Online (Sandbox Code Playgroud)
编辑:除了这一点,因为纳瓦兹指出,定义头文件string是<string>,不<cstring>.