class Test
{
public:const int MY_MASK;
Test() : MY_MASK(0xff) {}
};
如果不是在初始化列表中对 const 常量进行初始化,而是在构造函数中对其赋值的话,是不能成功的。很简单的道理:不能给 const 成员赋值。同样的道理,如果要初始化一个引用类型的成员变量,也不能在构造函数体内赋值,而只能在构造函数的初始化列表中进行初始化。
template<class T>
class NamedObject {
public:
<strong>NamedObject(string& name, const T& value): nameValue(name),objectValue(value)</strong>{ }
// 同上,假设没有
// 声明 operator=
private:
<strong>string& nameValue; // 现在是一个引用
const T objectValue; // 现在为 const</strong>
};
int main(int argc, char* argv[])
{
string newDog("Persephone");
string oldDog("Satch");
NamedObject<int> p(newDog, 2);
NamedObject<int> s(oldDog, 29);
}