概述
为了类的使用方便,类的设计尽可能使类的使用方式与内置类型无区别,构造函数则是类模仿内置类型的初始化
内置类型初始化支持直接初始化,复制初始化,默认初始化,构造函数对应于内置类型的各种初始化:
- 带参数构造函数——直接初始化
- 复制构造函数——复制初始化
- 默认构造函数——默认初始化
构造函数特点:
- 函数名与类名同名,用来标记和识别构造函数
- 没有返回值,构造函数是对自身的初始化,返回值无意义,因为没有返回值的接收者
- 初始化行为,构造函数在生成(定义)对象时自动调用,因此构造函数只能执行一次,否则就多次初始化
构造函数组成:
- 初始化列表和函数体
- 初始化列表完成初始化行为,初始化列表确保类的所有数据成员都得到合适的初始化
- 函数体与普通函数函数体无区别,函数体可进行一些深层定制,一般完成的都是一些简单功能
辅助类
class CAnimal
{
public:
CAnimal() : mGroup(0)
{
cout << "CAnimal()" << endl;
}
CAnimal(int group) : mGroup(group)
{
cout << "CAnimal(" << group << ")" << endl;
}
CAnimal(const CAnimal &other) : mGroup(other.mGroup)
{
cout << "CAnimal(const CAnimal &other)" << endl;
}
private:
int mGroup;
};
class CDog : public CAnimal
{
public:
CDog() : mLoyal(10)
{
cout << "CDog()" << endl;
}
CDog(int loyal) : CAnimal(1), mLoyal(loyal)
{
cout << "CDog(" << loyal << ")" << endl;
}
CDog(const CDog &other) : CAnimal(other), mLoyal(other.mLoyal)
{
cout << "CDog(const CDog &other)" << endl;
}
private:
int mLoyal;
};
class CCat : public CAnimal
{
public:
CCat() : mCute(20)
{
cout << "CCat()" << endl;
}
CCat(int cute) : CAnimal(2), mCute(cute)
{
cout << "CCat(" << cute << ")" << endl;
}
CCat(const CCat &other) : CAnimal(other), mCute(other.mCute)
{
cout << "CCat(const CCat &other)" << endl;
}
private:
int mCute;
};
class CPig : public CAnimal
{
public:
CPig() : mWeight(30)
{
cout << "CPig()" << endl;