#include <iostream>
using namespace std;
class Human
{
public:
Human()
{
cout << "Human无参构造" << endl;
}
Human(string a, int b) : name(a), age(b)
{
cout << "Human有参构造" << endl;
}
~Human()
{
cout << "Human析构函数" << endl;
}
void show()
{
cout << "Human::name " << name << endl;
cout << "Human::age " << age << endl;
cout << "Human show" << endl;
}
private:
string name = "范飞龙";
int age = 23;
};
class Student : public Human
{
public:
// 无参构造
Student() : Human()
{
cout << "Student无参构造" << endl;
}
// 初始化有参构造
Student(int a) : Human(), score(a)
{
cout << "Student无参构造" << endl;
}
// 有参构造
Student(string a, int b, int c) : Human(a, b), score(c)
{
cout << "Student有参构造" << endl;
}
// 析构函数
~Student()
{
cout << "Student析构函数" << endl;
}
private:
int score;
};
class Party : public Human
{
public:
// 无参构造
Party() : Human()
{
cout << "Party无参构造" << endl;
}
// 初始化有参构造
Party(string a, string b) : Human(), action(a), organization(b)
{
cout << "Party无参构造" << endl;
}
// 有参构造
Party(string a, int b, string c, string d) : Human(a, b), action(c), organization(d)
{
cout << "Party有参构造" << endl;
}
// 析构函数
~Party()
{
cout << "Party析构函数" << endl;
}
private:
string action;
string organization;
};
class cadre : public Student, public Party
{
public:
// 无参构造
cadre() : Student(), Party(), posts("")
{
cout << "cadre无参构造" << endl;
}
// 初始化有参构造
cadre(string a) : Student(), Party(), posts(a)
{
cout << "cadre无参构造" << endl;
}
// 有参构造
cadre(string a, int b, int c, string d, string e, string f): Student(a, b, c), Party(a, b, d, e), posts(f)
{
cout << "cadre有参构造" << endl;
}
// 析构函数
~cadre()
{
cout << "cadre析构函数" << endl;
}
private:
string posts;
};
// 子类继承父类的show()
void func(Human &s)
{
s.show();
}
void func2(Student &s)
{
s.show();
}
void func3(Party &s)
{
s.show();
}
int main(int argc, const char *argv[])
{
// 测试各实例对象中对父类的继承
cout << "Student test" << endl;
Student s1;
func(s1);
cout << "Party test" << endl;
Party p1;
func(p1);
cout << "cadre test1" << endl;
cadre c1;
func2(c1);
cout << "cadre test2" << endl;
func3(c1);
}
2024年9月4日 C++ 菱形继承
于 2024-09-04 19:39:10 首次发布