class A
{
public:
A():a({1,2})
{
};
private:
const int a[2];
};
編譯過不了!請幫忙解釋一下,謝謝
解釋:
1.類裡面的任何成員變數在定義時是不能初始化的。
2.一般的資料成員可以在建構函式中初始化。
3.const資料成員必須在建構函式的初始化列表中初始化。
4.static 要在類的定義外面初始化。
5.數群組成員是不能在初始化列表裡初始化的。
cannot specify explicit initializer for arrays
不能給數組指定明顯的初始化。
enum{i=10,a=100}; 可以達到要求,而且,const資料成員只在對象的內部是常量,而對於整個類來說就是可變的了!
referrence: The Constructor Initializer
The constructor initializer starts with a colon, which is followed by a comma-separated list of data members each of which is followed by an initializer inside parentheses.
The constructor initializer is specified only on the constructor definition, not its declaration.
Data members of class type are always initialized in the initialization phase, regardless of whether the member is initialized explicitly in the constructor initializer list. Initialization happens before the computation phase begins. |
Constructor Initializers Are Sometimes Required
Some members must be initialized in the constructor initializer. For such members, assigning to them in the constructor body doesn't work. Members of a class type that do not have a default constructor and members that are const or reference types must be initialized in the constructor initializer regardless of type. |
Advice: Use Constructor Initializers In many classes, the distinction between initialization and assignment is strictly a matter of low-level efficiency: A data member is initialized and assigned when it could have been initialized directly. More important than the efficiency issue is the fact that some data members must be initialized.
We must use an initializer for any const or reference member or for any member of a class type that does not have a default constructor. |
By routinely using constructor initializers, we can avoid being surprised by compile-time errors when we have a class with a member that requires a constructor initializer. |
Order of Member Initialization
The order of initialization often doesn't matter. However, if one member is initialized in terms of another, then the order in which members are initialized is crucially important. |
It is a good idea to write constructor initializers in the same order as the members are declared. Moreover, when possible, avoid using members to initialize other |
Initializers May Be Any Expression
An initializer may be an arbitrarily complex expression.