#include <iostream>
using namespace std;
//学生类
class Stu {
private:
string name;
int age;
double score;
public:
Stu() :name(""), age(18), score(0) { cout << "Stu::无参构造" << endl; } //无参构造
Stu(string n, int a, double s):name(n), age(a), score(s){ cout << "Stu::有参构造" << endl; } //有参构造
~Stu() { cout << "S析构" << endl; } //析构函数
void show() //展示函数
{
cout << name << endl;
cout << age << endl;
cout << score << endl;
}
};
//党员类
class Party {
private:
string activity;
string organization;
public:
Party():activity(""), organization(""){ cout << "Party::无参构造" << endl; } //无参构造
Party(string ac, string o):activity(ac), organization(o) { cout << "Party::有参构造" << endl; } //有参构造
~Party() { cout << "P析构" << endl; } //析构函数
void show() //展示函数
{
cout << activity << endl;
cout << organization << endl;
}
};
//干部类,继承学生和党员类
class Cadre :public Stu, public Party{
private:
string position;
public:
Cadre():position(""){ cout << "Cadre::无参构造" << endl; } //无参构造
//调用有参构造,初始化所有成员,调用(父类)构造函数顺序只和继承顺序有关
Cadre(string s, int a, double so, string ac, string o, string c):Stu(s, a, so),Party(ac, o), position(c){ cout << "Cadre::有参构造" << endl; } //有参构造
~Cadre(){ cout << "C析构" << endl; } //析构函数
void show() //展示函数
{
Stu::show();
Party::show();
cout << position << endl;
}
};
int main(void)
{
//实例化对象
Cadre c1("xinyue", 18, 88, "小型马拉松", "青年社团", "团长");
c1.show();
return 0;
}
1,实例化对象时,构造函数的调用顺序
如下图所示,实例化对象时,会按照继承的顺序(谁在前,先被调用)来调用对应的构造函数,对于析构函数,在栈区中,则是先创建的后析构,后创建的先析构。
2,同名函数
在干部类中,分别继承了学生类与党员类的show函数,如果名字与自身函数名相同,会产生递归,如下图所示
如果名字不同,则会报出混淆错误,系统不知道调用哪一个,所以必须加一区分。
如下图所示,加以区分: