2012-08-08 53 views
0
#include <utility> 
class C { 
    private: 
    const std::pair<int,int> corner1(1,1); 
}; 

GCC報告錯誤:數字常量之前的預期標識符。如何在我的頭文件中聲明一個常量對

我需要在它聲明的時候構造對象,因爲它是const的,但我似乎無法得到正確的語法。

回答

1

I need to construct the object on the moment of it's declaration since it's const, but I can't seem it get the right syntax.

不行,你只能初始化非整數類型 - const或沒有(至少前C++ 11)在構造函數初始化列表:

class C { 
    private: 
    const std::pair<int,int> corner1; 
    C() : corner1(1,1) {} 
}; 

但似乎對我來說,你不需要複製的成員在每一個實例,所以我只是讓靜態的,而不是:

class C { 
    private: 
    static const std::pair<int,int> corner1; 
}; 

//implementation file: 
const std::pair<int,int> C::corner1(1,1); 
0

如果你通過-std=c++11和你正在使用gcc的一個較新的版本,你可以這樣做:

class C { 
    private: 
    const std::pair<int,int> corner1{1,1}; // Note curly braces 
};