C++多重继承
1.1一个派生类继承多个基类称为多重继承。
1.2声明多重继承的方法。
如果声明了类A,B,C,可以声明多重派生类D。
class D:public A,private B,protected C
{类D新增加的成员}
1.2多重继承派生类的构造函数,如:
派生类构造函数名(总参数表列):基类1构造函数(参数表列),基类2构造函数(参数表列),基类3构造函数(参数表列)
{派生类中新增成员的初始化语句}
#include <iostream>
#include <string>
using namespace std;
class student
{
public:
student(string n,bool s,float sco):name(n),sex(s),score(sco){}
protected:
string name;
bool sex;
float score;
};
class teacher
{
public:
teacher(string n,string t,int a):name1(n),title(t),age(a){}
protected:
string name1;
string title;
int age;
};
class graduate:public student,public teacher
{
public:
graduate(string n,bool s,float sco,string t,int a,float w):student(n,s,sco),teacher(n,t,a),wage(w){}
void show();
private:
float wage;
};
void graduate::show()
{
cout << "name: " << name << endl;
cout << "sex: " << sex << endl;
cout << "score: " << score << endl;
cout << "title: " << title << endl;
cout << "wage: " << wage << endl;
}
int main()
{
graduate gra("fuck",true,100,"shit",20,9999999);
gra.show();
return 0;
}
C++多重继承引起的二义性问题
1.1多重继承经常会由于继承成员同名而产生二义性问题。
1.2我们可以用域运算符::,来限定:
c.A::age=5; //引用c对象中基类A的数据成员a
1.3派生类中同名成员会覆盖基类中的同名成员。
1.4不同的成员函数,只有在函数名和参数个数相同,类型相匹配的情况下,才会发生同名覆盖,如果只有函数名相同而参数不同,不会发生同名覆盖,而属于函数重载。
1.5一段代码:
#include <iostream>
using namespace std;
class A
{
public:
void display(){cout << age << endl;}
int age;
};
class B
{
public:
void display(){cout << age << endl;}
int age;
};
class C:public A,public B
{
public:
C(int c):ceat(c){}
void show(){cout << A::age << "c" << endl;}
int age;
private:
int ceat;
};
int main()
{
C c(5);
c.age=1;
c.A::age=5;
c.show();
return 0;
}