2012-03-24 88 views
1
#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++靜態屬性初始化錯誤

+2

該問題已經回答,但只是在下一次:說出什麼錯誤得到確切。 – 2012-03-24 12:54:14

+0

@MrLister現在工作正常。但是我想知道const如何在以後被宣佈! – Dewsworld 2012-03-24 13:09:49

回答

8

非整體式部件(其包括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>

+1

這不是「用戶定義的成員」。在C++ 03中,它是「非整型類型」,在C++ 11中,它沒有任何常量表達式初始化。 – 2012-03-24 12:57:42

+0

@KerrekSB:實際上,只有* static const整數和枚舉*可以在C++ 03中進行類內初始化。 – 2012-03-24 13:02:02

+1

@Als爲什麼'char'爲他工作? – 2012-03-24 13:02:32

3
  • 第一件事第一件事。您尚未包含<string>。所以,這樣做第一:

    #include <string> 
    

    std::string<string>定義,而不是在<cstring>正如你可能想象。

  • 之後,在C++ 03中,類的非整型靜態成員的初始化必須在類之外。

  • 在C++ 11中,如果只包含<string>,代碼將會被編譯。無需在課堂外定義靜態成員。

+2

+1在C++ 11中,您可以初始化類定義中的任何靜態? – 2012-03-24 12:55:20

+0

@LuchianGrigore:是的。 – Nawaz 2012-03-24 12:57:11

+0

@Nawaz感謝它的工作。但是我懷疑** **然後呢?因爲我認爲它有點*現代*字符串版本! – Dewsworld 2012-03-24 13:14:07