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

本文实例讲述了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++多重继承引发的重复调用问题与解决方法

相关文章:

你感兴趣的文章:

标签云: