如前所述,您需要使用其初始化列表来初始化对象的 const 成员:
/* a.h */
class A {
private:
const string cs;
public:
A(const string &value) :
cs(value) // <---- initialize here!.
{};
};
类的每个 const 成员都是一样的:
class A {
private:
const string cs;
const float numberofthebeast;
const char z;
public:
A(const string &value, const float number, const char character) :
cs(value),
numberofthebeast(number),
z(character)
{};
};
如果不想提供构造函数来初始化每个值,可以在默认构造函数中提供默认值,但请记住,构造后不能更改值:
class A {
private:
const string cs;
const float numberofthebeast;
const char z;
public:
A(const string &value, const float number, const char character) :
cs(value),
numberofthebeast(number),
z(character)
{};
// Default values!!!
A() :
cs("default ctor"),
numberofthebeast(666.666f),
z('Z')
{};
};
构造函数初始化器列表对于初始化其他成员也很有用,例如引用或不提供默认构造函数的复杂数据:
const unsigned float PI = 3.14f;
class Weird
{
Weird (int w);
// no default ctor!
int W;
};
class Foo
{
// Error: weird doesn't provide default ctor,
Weird w;
// Error: reference uninitialized.
float π
};
class Bar
{
Bar() :
// Ok, Weird is constructed correctly.
w(1),
// Ok, pi is initialized.
pi(PI)
{};
Weird w;
float π
};