初始化列表与赋值
- const成员的初始化只能在构造函数初始化列表中进行
40 分钟
初始化列表与赋值
- const成员的初始化只能在构造函数初始化列表中进行
- 引用成员的初始化也只能在构造函数初始化列表中进行
- 对象成员(对象成员所对应的类没有默认构造函数)的初始化,也只能在构造函数初始化列表中进行
类之间嵌套
第一种: 使用初始化列表。
class Animal {
public:
Animal() {
std::cout << "Animal() is called" << std::endl;
}
Animal(const Animal &) {
std::cout << "Animal (const Animal &) is called" << std::endl;
}
Animal &operator=(const Animal &) {
std::cout << "Animal & operator=(const Animal &) is called" << std::endl;
return *this;
}
~Animal() {
std::cout << "~Animal() is called" << std::endl;
}
};
class Dog {
public:
Dog(const Animal &animal) : __animal(animal) {
std::cout << "Dog(const Animal &animal) is called" << std::endl;
}
~Dog() {
std::cout << "~Dog() is called" << std::endl;
}
private:
Animal __animal;
};
int main() {
Animal animal;
std::cout << std::endl;
Dog d(animal);
std::cout << std::endl;
return 0;
}
运行结果:
Animal() is called
Animal (const Animal &) is called
Dog(const Animal &animal) is called
~Dog() is called
~Animal() is called
~Animal() is called
依次分析从上到下:
main函数中Animal animal;调用默认构造。
Dog d(animal);等价于:
Animal __animal = animal;
实际上就是调用了拷贝构造,因此输出了:
Animal (const Animal &) is called
再然后打印Dog的构造函数里面的输出。
最后调用析构,程序结束。
第二种:构造函数赋值来初始化对象。
构造函数修改如下:
Dog(const Animal &animal) {
__animal = animal;
std::cout << "Dog(const Animal &animal) is called" << std::endl;
}
此时输出结果:
Animal() is called
Animal() is called
Animal & operator=(const Animal &) is called
Dog(const Animal &animal) is called
~Dog() is called
~Animal() is called
~Animal() is called
于是得出:
当调用Dog d(animal);时,等价于:
先定义对象,再进行赋值,因此先调用了默认构造,再调用=操作符重载函数。
// 假设之前已经有了animal对象
Animal __animal;
__animal = animal;
小结