C++多重继承引发的重复调用问题与解决方法

Aine ·
更新时间:2024-09-21
· 503 次阅读

本文实例讲述了C++多重继承引发的重复调用问题与解决方法。分享给大家供大家参考,具体如下:

前面简单介绍了一个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++程序设计有所帮助。

您可能感兴趣的文章:C++编写生成不重复的随机数代码C++利用容器查找重复列功能实现用位图排序无重复数据集实例代码(C++版)C/C++语言中全局变量重复定义问题的解决方法C++移除序列中连续重复的特定值示例代码



继承 c+ 方法 调用 多重继承 C++

需要 登录 后方可回复, 如果你还没有账号请 注册新账号
相关文章
Uma 2020-10-21
610