多重继承派生类的构造函数
- 分别声明teacher(教师)类和 cadre(干部类),采用多种继承方式由这两个类派生出新类teacher_cadre(教师兼干部)类。要求:
(1)在两个基类中都包含姓名、年龄、性别等数据成员
(2)在teacher类中还包含数据成员title(职称),在cadre类中还包含数据成员post(职务)。在teacher_cadre中还包含数据成员wages(工资)。
(3)对两个基类中的姓名、年龄,性别等数据成员用相同的名字,在引用这些数据成员时,指定作用域。
(4)在类体中生命成员函数,在类外定义成员函数。
(5)在派生类teacher_cadre的成员函数show中调用teacher类中的display函数,输出姓名、年龄、性别,然后再用cout语句输出职务于工资。
#include<iostream>
using namespace std;
class teacher
{public:
teacher(string nam, int a, string t, string s)
{ name = nam;
age = a;
title = t;
sex = s;}
void display()
{ cout << "name: " << name <<endl;
cout << "age: " << age << endl;
cout << "title: " <<title << endl;
cout << "sex: " << sex << endl; }
protected:
string name;
int age;
string title;
string sex;
};
class cadre
{public:
cadre(string nam,int a, string s,string p)
{name = nam;
age = a;
sex = s;
post = p;}
void display1()
{cout << "name: " << name <<endl;
cout << "age: " << age << endl;
cout << "post: " <<post << endl;
cout << "sex: " << sex << endl; }
protected:
string name;
int age;
string post;
string sex;
};
class company:public teacher,public cadre
{ public:
company(string nam, int a,string s, string t,string p, float w):
teacher(nam,a,s, t),cadre(nam,a,s,p),wage(w) {}
void show()
{ teacher::display();
cout << "post: " << post << endl;
cout << "wage: " << wage <<endl;
}
private:
float wage;
};
int main()
{company com1("Yuki",18,"assisitant", "f", "manager",23000);
com1.show();
return 0;
}
程序运行结果
name: Yuki
age: 18
title: assisitant
sex: f
post: manager
wage: 23000
Process returned 0 (0x0) execution time : 0.040 s
Press any key to continue.
虚基类的简单应用举例
#include<iostream>
using namespace std;
calss person
{public:
person(string nam,char s,int a)
{name = nam,sex = s;age = a;}
protected:
string name;
char sex;
int age;
};
class teacher : virtual public person
{public:
teacher(string nam,char s,int a, string t):person(nam,s,a)
{title = t;}
protected:
string title;
};
class student :virtual public person
{public:
student (string nam,char s,int a,float sco):person(nam,s,a),score(sco){}
protected:
float score;
};
class graduate:public teacher,public student
{public:
graduate(string nam,char s,int a,string t,float sco,float w)
:person(nam,s,a),teacher(nam,s,a,t),student(nam,s,a,sco),wage(w){}
void show()
{cout << "name: " << name << " age: " << age <<" sex: " << sex << " score: "<< " title: " << title << " wage: " << wage << endl;}
private:
float wage;
};
int main()
{graduate grad1("张飞",'m' ,26,"assistant",89.3,2300);
grad1.show();
return 0;
}
程序运行结果
name: violet age: 26 sex: m score: title: assistant wage: 2300
Process returned 0 (0x0) execution time : 0.014 s
Press any key to continue.