国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C++ > 正文

C++多重繼承引發(fā)的重復(fù)調(diào)用問題與解決方法

2020-05-23 13:30:38
字體:
供稿:網(wǎng)友

本文實(shí)例講述了C++多重繼承引發(fā)的重復(fù)調(diào)用問題與解決方法。分享給大家供大家參考,具體如下:

前面簡單介紹了一個(gè)C++多重繼承功能示例,這里再來分析一個(gè)多重繼承引發(fā)的重復(fù)調(diào)用問題,先來看看問題代碼:

#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()函數(shù)  void f()  {    cout << "a = " << a << endl;    R::f();//r是私有成員變量,不能直接訪問,通過作用域進(jìn)行訪問被派生類覆蓋的函數(shù)f()  }};//虛繼承class B : virtual public R{private:  int b;public:  B(int x, int y) :R(x), b(y) {}  //重寫父類的f()函數(shù)  void f()  {    cout << "b = " << b << endl;    R::f();//r是私有成員變量,不能直接訪問,通過作用域進(jìn)行訪問被派生類覆蓋的函數(shù)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();//此時(shí)A里面有一個(gè) r 的輸出,和輸出a    B::f();//B里面也有一個(gè)r的輸出,和輸出b    //從而導(dǎo)致重復(fù)調(diào)用,兩次輸出 r  }};int main(){  C cc(1212, 345, 123, 45);  cc.f();  system("pause");  return 0;}

解決辦法:針對重復(fù)調(diào)用,每個(gè)類把屬于自己的工作單獨(dú)封裝

修改后的代碼如下:

#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()//增加一個(gè)保護(hù)函數(shù),只打印自己的擴(kuò)展成員  {    cout << "a = " << a << endl;  }  void f()//重寫父類的f()函數(shù)  {    //cout << "a = " << a << endl;    fA();    R::f();//r是私有成員變量,不能直接訪問,通過作用域進(jìn)行訪問被派生類覆蓋的函數(shù)f()  }};//虛繼承class B : virtual public R{private:  int b;public:  B(int x, int y) :R(x), b(y) {}protected:  void fB()//增加一個(gè)保護(hù)函數(shù),只打印自己的擴(kuò)展成員  {    cout << "b = " << b << endl;  }  void f()//重寫父類的f()函數(shù)  {    fB();    R::f();//r是私有成員變量,不能直接訪問,通過作用域進(jìn)行訪問被派生類覆蓋的函數(shù)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();//此時(shí)A里面有一個(gè) r 的輸出,和輸出a    //B::f();//B里面也有一個(gè)r的輸出,和輸出b    //從而導(dǎo)致重復(fù)調(diào)用,兩次輸出 r    fA();//A::fA();    fB();//A::fB();  }};int main(){  C cc(1212, 345, 123, 45);  cc.f();  system("pause");  return 0;}

希望本文所述對大家C++程序設(shè)計(jì)有所幫助。


發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 长治县| 乌拉特前旗| 东乌珠穆沁旗| 大冶市| 新泰市| 呈贡县| 大荔县| 巴中市| 崇左市| 云安县| 呼和浩特市| 黔西| 永年县| 安义县| 芜湖县| 来凤县| 沁阳市| 昔阳县| 大安市| 吕梁市| 文水县| 西平县| 英超| 金溪县| 日土县| 壶关县| 蛟河市| 南汇区| 武鸣县| 青海省| 台湾省| 循化| 舒城县| 东安县| 临安市| 兴和县| 泰来县| 夏津县| 泗阳县| 丹东市| 丹东市|