For example, the following constructor is in error:
class ConstRef {
public:
ConstRef(int ii);
private:
int i;
const int ci; //常量
int &ri; //引用
};
// no explicit constructor initializer: error ri is uninitialized
ConstRef::ConstRef(int ii)
{ // assignments:
i = ii; // ok
ci = ii; // error: cannot assign to a const
ri = i; // assigns to ri which was not bound to an object
}
Remember that we can initialize but not assign to const objects or objects of reference type. By the time the body of the constructor begins executing, initialization is complete. Our only chance to initialize const or reference data members is in the constructor initializer. The correct way to write the constructor is
// ok: explicitly initialize reference and const members ConstRef::ConstRef(int ii): i(ii), ci(i), ri(ii) { }
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.
本文探讨了C++中构造函数的正确使用方式,特别是对于常量成员和引用成员的初始化。文章强调了初始化与赋值的区别,并展示了如何通过构造函数初始化列表来避免编译错误。
2168

被折叠的 条评论
为什么被折叠?



