本文實(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ì)有所幫助。
新聞熱點(diǎn)
疑難解答