C++之多重继承引发的重复调用

#include "stdafx.h"
#include<stdlib.h>
#include<iostream>
using namespace std;

class R//祖先类
{
private:
	int r;
public:
	R(int x = 0):r(x){}
	void f()
	{
		cout << " r = " << r << endl;
	}
	void print()
	{
		cout << "print R = " << r << endl;
	}
};
//虚继承
class A : virtual  public R
{
private:
	int a;
public:
	A(int x,int y):R(x),a(y){}
	//重写父类的f()函数
	void f()
	{
		cout << "a = " << a << endl;
		R::f();//r是私有成员变量,不能直接访问,通过作用域进行访问被派生类覆盖的函数f()
	}
};
//虚继承
class B : virtual  public R
{
private:
	int b;
public:
	B(int x, int y) :R(x), b(y) {}
	//重写父类的f()函数
	void f()
	{
		cout << "b = " << b << endl;
		R::f();//r是私有成员变量,不能直接访问,通过作用域进行访问被派生类覆盖的函数f()
	}
};
class C :public A, public B
{
private: 
	int c;
public:
	C(int x,int y,int z,int m):R(x),A(x,y),B(x,z),c(m)
	{  }
	void f()
	{
		cout << "c = " << c << endl;
		A::f();//此时A里面有一个  r  的输出,和输出a
		B::f();//B里面也有一个r的输出,和输出b
		//从而导致重复调用,两次输出 r 
	}

};
int main()
{
	C cc(1212, 345, 123, 45);
	cc.f();

	system("pause");
	return 0;
}


//解决办法:针对重复调用,每个类把属于自己的工作单独封装

#include "stdafx.h"
#include<stdlib.h>
#include<iostream>
using namespace std;

class R//祖先类
{
private:
	int r;
public:
	R(int x = 0):r(x){}
	void f()
	{  cout << " r = " << r << endl;        }
	virtual void print()
	{  cout << "print R = " << r << endl;}
};
//虚继承
class A : virtual  public R//virtual写在public的前后均可以
{
private:
	int a;
public:
	A(int x,int y):R(x),a(y){  }

protected:
	void fA()//增加一个保护函数,只打印自己的扩展成员
	{
		cout << "a = " << a << endl;
	}
	
	void f()//重写父类的f()函数
	{
		//cout << "a = " << a << endl;
		fA();
		R::f();//r是私有成员变量,不能直接访问,通过作用域进行访问被派生类覆盖的函数f()
	}
};
//虚继承
class B : virtual  public R
{
private:
	int b;
public:
	B(int x, int y) :R(x), b(y) {}

protected:
	void fB()//增加一个保护函数,只打印自己的扩展成员
	{
		cout << "b = " << b << endl;
	}
	
	void f()//重写父类的f()函数
	{
		fB();
		R::f();//r是私有成员变量,不能直接访问,通过作用域进行访问被派生类覆盖的函数f()
	}
};
class C :public A, public B
{
private: 
	int c;
public:
	C(int x,int y,int z,int m):R(x),A(x,y),B(x,z),c(m)
	{  }
	void f()
	{
		cout << "c = " << c << endl;
		R::f();
		//A::f();//此时A里面有一个  r  的输出,和输出a
		//B::f();//B里面也有一个r的输出,和输出b
		//从而导致重复调用,两次输出 r 

		fA();//A::fA();
		fB();//A::fB();

	}

};
int main()
{
	C cc(1212, 345, 123, 45);
	cc.f();

	system("pause");
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值