题目:
1.定义一个人类(Human):私有成员(姓名,年龄)、成员方法((无参构造、有参构造、析构函数、show函数)
2.由人类派生出一个学生类(Student):私有成员属性(分数)、成员方法(无参构造、有参构造、析构函数、show函数)
3.由人类派生出一个党员类(Party):私有成员属性(党组织活动,组织),成员方法(无参构造、有参构造、析构函数、show函数)。
4.由这两个类共同派生出学生干部类,私有成员属性(职位),成员方法(无参构造、有参构造、析构函数、show函数),使用学生干部类实例化一个对象,然后调用其show函数进行测试
#include <iostream> #include <string> #include <cstring> using namespace std; //定义父类(人类human) class Human { public: //无参构造函数 Human(){cout << "Human--无参构造" << endl;} //有参构造函数 Human(string name,int age):name(name),age(age) { cout << "Human--有参构造" << endl; } //析构函数 ~Human(){cout << "Human--析构" << endl;} //show函数 void show() { cout << "Human:" << endl; cout << "name= " << name << endl; cout << "age= " << age << endl; } private: int age; string name; }; class Student:virtual public Human //virtual虚继承 { public: //无参构造函数 Student(){cout << "Student--无参构造" << endl;} //有参构造函数 Student(string name,int age,int score):Human(name,age),score(score) { cout << "Student--有参构造" << endl; } //析构函数 ~Student(){cout << "Student--析构" << endl;} //show函数 void show() { cout << "Student:" << endl; cout << "score= " << score << endl; } private: int score; }; class Party:virtual public Human //virtual虚继承 { public: //无参构造函数 Party(){cout << "Party--无参构造" << endl;} //有参构造函数 Party(string name,int age,string org,string act):Human(name,age),organization(org),activity(act) { cout << "Party--有参构造" << endl; } //析构函数 ~Party(){cout << "Party--析构" << endl;} //show函数 void show() { cout << "Party:" << endl; cout << "organization= " << organization << endl; cout << "activity= " << activity << endl; } private: string organization; string activity; }; class Cadres:public Student,public Party { public: //无参构造函数 Cadres(){cout << "Cadres--无参构造" << endl;} //有参构造函数 Cadres(string name,int age,int score,string org,string act,string pos): Human(name,age),Student(name,age,score),Party(name,age,org,act),position(pos) { cout << "Cadres--有参构造" << endl; } //析构函数 ~Cadres(){cout << "Cadres--析构" << endl;} //show函数 void show() { Human::show(); Student::show(); Party::show(); cout << "Cadres:" << endl; cout << "position= " << position << endl; } private: string position; }; int main(int argc,char** argv) { Cadres c1; cout << "********************************" << endl; //name age score organization activity position Cadres c2("林七夜",19,99,"精神病院","治愈","神明代理人"); c2.show(); cout << "********************************" << endl; //计算类的大小 cout << "sizeof(Human):" << sizeof(Human) << endl; cout << "sizeof(Student):" << sizeof(Student) << endl; cout << "sizeof(Party):" << sizeof(Party) << endl; cout << "sizeof(Cadres):" << sizeof(Cadres) << endl; return 0; }
结果:
嵌入式-C++--虚继承(virtual)
于 2024-09-04 22:45:44 首次发布