若要自定义类初始化其成员的方式,或是如要在创建类的对象时调用函数,请定义构造函数。 构造函数具有与类相同的名称,没有返回值。 可以定义所需数量的重载构造函数,以各种方式自定义初始化。 通常,构造函数具有公共可访问性,以便类定义或继承层次结构外部的代码可以创建类的对象。 但也可以将构造函数声明为 protected
或 private
。
构造函数可以选择采用成员初始化表达式列表。 与在构造函数主体中赋值相比,初始化类成员是更高效的方式。 以下示例演示具有三个重载构造函数的类 Box
。 最后两个构造函数使用成员初始化列表:
class Box {
public:
// Default constructor
Box() {}
// Initialize a Box with equal dimensions (i.e. a cube)
explicit Box(int i) : m_width(i), m_length(i), m_height(i) // member init list
{}
// Initialize a Box with custom dimensions
Box(int width, int length, int height)
: m_width(width), m_length(length), m_height(height)
{}
int Volume() { return m_width * m_length * m_height; }
private:
// Will have value of 0 when default constructor is called.
// If we didn't zero-init here, default constructor would
// leave them uninitialized with garbage values.
int m_width{ 0 };
int m_length{ 0 };
int m_height{ 0 };
};
也可以采用下面的方式进行初始构造,是一样的
class Box {
public:
// Default constructor
Box() {}
// Initialize a Box with equal dimensions (i.e. a cube)
explicit Box(int i) : m_width(i), m_length(i), m_height(i) // member init list
{}
// Initialize a Box with custom dimensions
Box(int width, int length, int height){
m_width = width);
m_length(length);
m_height(height);
}
int Volume() { return m_width * m_length * m_height; }
private:
// Will have value of 0 when default constructor is called.
// If we didn't zero-init here, default constructor would
// leave them uninitialized with garbage values.
int m_width{ 0 };
int m_length{ 0 };
int m_height{ 0 };
};