这篇文章主要介绍如何解决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;
}
以上是“如何解决C++多重继承引发的重复调用的问题”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。