1. 在Star的构造函数前导中,我们必须给CelestialBody的构造函数传递参数。方法是使用它的类名调用基构造函数
Star(double mass, double brightness) : CelestialBody(mass), _brightness(brightness)
2. 构建顺序:首先完全构建基类,然后再构建派生类
3. 派生类的构建顺序通常是:首先是嵌入体,然后是构造函数中的显式代码
4. 前导中的顺序无意义,而且如果不存在显式初始化,前导中全部内容可以被忽略
5. 析构顺序与构建顺序相反,即首先调用派生类的析构函数,再调用基类的析构函数
Star is-a CelestialBody
输出结果:
Entering main.
Creating celestial body of mass 1234.5
Creating a star of brightness 0.1
Exiting main.
Destroying a star of brightness 0.1
Destroying celestial body of mass 1234.5
Star(double mass, double brightness) : CelestialBody(mass), _brightness(brightness)
2. 构建顺序:首先完全构建基类,然后再构建派生类
3. 派生类的构建顺序通常是:首先是嵌入体,然后是构造函数中的显式代码
4. 前导中的顺序无意义,而且如果不存在显式初始化,前导中全部内容可以被忽略
5. 析构顺序与构建顺序相反,即首先调用派生类的析构函数,再调用基类的析构函数
Star is-a CelestialBody
#include <iostream>
class CelestialBody
{
public:
CelestialBody(double mass) : _mass(mass)
{
std::cout<<"Creating celestial body of mass "<<_mass<<"\n";
}
~CelestialBody()
{
std::cout<<"Destroying celestial body of mass "<<_mass<<"\n";
}
private:
const double _mass;
};
class Star : public CelestialBody //Star是一个CelestialBody
{
public:
Star(double mass, double brightness) : CelestialBody(mass), _brightness(brightness)
{
std::cout<<"Creating a star of brightness "<<_brightness<<"\n";
}
~Star()
{
std::cout<<"Destroying a star of brightness "<<_brightness<<"\n";
}
private:
const double _brightness;
};
void main()
{
std::cout<<" Entering main.\n";
Star aStar(1234.5, 0.1);
std::cout<<" Exiting main.\n";
}
class CelestialBody
{
public:
CelestialBody(double mass) : _mass(mass)
{
std::cout<<"Creating celestial body of mass "<<_mass<<"\n";
}
~CelestialBody()
{
std::cout<<"Destroying celestial body of mass "<<_mass<<"\n";
}
private:
const double _mass;
};
class Star : public CelestialBody //Star是一个CelestialBody
{
public:
Star(double mass, double brightness) : CelestialBody(mass), _brightness(brightness)
{
std::cout<<"Creating a star of brightness "<<_brightness<<"\n";
}
~Star()
{
std::cout<<"Destroying a star of brightness "<<_brightness<<"\n";
}
private:
const double _brightness;
};
void main()
{
std::cout<<" Entering main.\n";
Star aStar(1234.5, 0.1);
std::cout<<" Exiting main.\n";
}
输出结果:
Entering main.
Creating celestial body of mass 1234.5
Creating a star of brightness 0.1
Exiting main.
Destroying a star of brightness 0.1
Destroying celestial body of mass 1234.5