2012-08-08 66 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 
};