2
1.菱形继承
中介继承继承虚基类时用
class Teacher:virtual public Cstaff
派生类继承中间的时候用public
CTeacherManagement::CTeacherManagement(int num, const char* na, int a, const char* zc, const char* z) :CStaff(num, na, a),CTeacher(num, na, a, zc), CManagement(num, na, a, z)
{
number = num;
age = a;
strcpy(name, na);
strcpy(zw, z);
strcpy(zch, zc);
}
int main()
{
CStaff s1(101,"Zhao",20);
CTeacher t1(102,"Zhang",30,"Lecture");
CManagement m1(103,"Wang", 50,"dean");
CTeacherManagement tm1(104,"Li",40, "Peofessor", "department head");
s1.Display();
t1.Display();
m1.Display();
tm1.Display();
return 0;
}
2.虚基类
#include <iostream>
using namespace std;
class vehicle{
protected:
double speed; //速度,公里/小时
int wheels; //轮子数
double weight; //重量
public:
vehicle(double speed=80,int wheels=4,double weight=1000);
virtual void show(void)=0;
public:
virtual ~vehicle(){} //析构函数为虚函数
};
vehicle::vehicle(double speed, int wheels , double weight )
: speed(speed), wheels(wheels), weight(weight) {
}
class car : public vehicle
{ int passenger_load;
public:
car(double speed=80,int wheels=4,double weight=1000,int passenger_load=4);
virtual void show(void);
public:
virtual ~car() {}
};
car::car(double speed , int wheels , double weight ,int passenger_load)
: vehicle(speed, wheels, weight),passenger_load(passenger_load) {
}
void car::show(void)
{cout << "Car message\n";
cout<<speed<<" "<<wheels<<" "<<weight<<" "<<passenger_load<<endl;
}
class truck : public vehicle
{ double rated_load; //额定载重
public:
truck(double speed=80,int wheels=4,double weight=2500,double rated_load=3000);
virtual void show(void);
virtual ~truck() {}
};
void truck::show(void)
{cout << "truck message\n";
cout<<speed<<" "<<wheels<<" "<<weight<<" "<<rated_load<<endl;
}
truck::truck(double speed,int wheels,double weight,double rated_load)
: vehicle(speed, wheels, weight),rated_load(rated_load) {
}
class boat : public vehicle
{ char kind; //轮船类别,如客轮为'k'
public:
boat(double speed=30,int wheels=0,double weight=12000,char kind='k');
virtual void show(void);
virtual ~boat() {}
};
void boat::show(void)
{cout << "boat message\n";
cout<<speed<<" "<<wheels<<" "<<weight<<" "<<kind<<endl;
}
boat::boat(double speed,int wheels,double weight,char kind)
: vehicle(speed, wheels, weight) ,kind(kind){
}
int main()
{ vehicle *unicycle; car *BMW;
unicycle = new car; unicycle ->show();
BMW= (car *) unicycle; BMW ->show();
delete unicycle;
unicycle = new truck; unicycle ->show();
delete unicycle;
unicycle = new boat; unicycle ->show();
delete unicycle;
return 0;
}
函数声明的时候可以赋默认值,但是后面定义的时候就不要赋默认数值了
vehicle *unicycle; car *BMW;
unicycle = new car; unicycle ->show();
BMW= (car *) unicycle; BMW ->show();
delete unicycle;
虚基类中直接virtual void show(void)=0;
还有boat类中的
boat::boat(double speed,int wheels,double weight,char kind)
: vehicle(speed, wheels, weight) ,kind(kind){
}