C++中的多重继承问题

1.什么是多重继承

        一个派生类可以有两个或多个基类(父类)

2.多重继承方法

         将多个基类用逗号隔开

#include<iostream>
#include<string>
using namespace std;

class Father {
public:
	Father(string name, int age);
	~Father();
private:
	string name;
	string age;
};

Father::Father(string name, int age) {
	this->name = name;
	this->age = age;
}

Father::~Father() {

}

class Monther {
public:
	Monther(string food);
	~Monther();
private:
	string food;
};

Monther::Monther(string food) {
	this->food = food;
}
Monther::~Monther() {

}

//继承顺序会决定派生类构造函数的调用顺序  先father后mother
class son :public Father, public Monther {
public:
	son(string name, int age, string food, string game);
	~son();
private:
	string game;
};

son::son(string name, int age, string food, string game) :
	Father(name, age), Monther(food) {
	this->game = game;
}

son::~son() {

}

 多重继承的二义性问题

class Father {
    public:
        fun();
}

class Monther{
    public:
        fun();
}

class son: public Father ,public Monther{
 
}

//当派生类继承重名成员时
//第一种方法:使用“类名::”指定从哪个基类继承的方法
son  s1;
s1.Father::fun();
class Father {
    public:
        fun();
}

class Monther{
    public:
        fun();
}

class son: public Father ,public Monther{
    public:
    void fun();
 
}


//当派生类继承重名成员时
//第二种方法:在子类中重实现这个同名方法,并在这个方法内部,使用基类名进行限定

void son::fun(){
    Father::fun();
    Monther::fun();
}


son  s1;
s1.fun();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值