1 创建子类对象时,父类的构造函数先于子类构造函数被调用。(析构时,子类的析构函数先被调用)
2 如果父类有多个构造函数,在子类构造函数中若未指定,则调用父类的默认构造函数或者无参构造函数。否则,按照子类构造函数中指定的父类构造函数类型调用。请看下例
#include <iostream>
#include <string>
using namespace std;
class Weapon {
public:
Weapon()
{
cout << "Weapon constructor" << endl;
}
Weapon(int value, string name) : m_value(value), m_name(name)
{
cout << "Weapon constructor"
<< ", value is: " << m_value
<< ", name is: " << m_name
<< endl;
}
virtual ~Weapon()
{
cout << "Weapon destructor" << endl;
}
private:
int m_value;
string m_name;
};
class Sold : public Weapon {
public:
Sold(float damage) : m_damage(damage) , Weapon(10, "killer") {
cout << "Sold constructor"
<< ", damage is: "
<< m_damage
<< endl;
}
virtual ~Sold()
{
cout << "Sold destructor" << endl;
}
private:
float m_damage;
};
int main()
{
Sold sold(27.8);
return 0;
}
运行结果:
Weapon constructor, value is: 10, name is: killer
Sold constructor, damage is: 27.8
Sold destructor
Weapon destructor
|