C++多重继承

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;
}
 
  
 
  

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值