C++ 多继承中的多义性
生活随笔
收集整理的這篇文章主要介紹了
C++ 多继承中的多义性
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
如果一個子類繼承多個基類,這多個基類都有一個相同的函數,那么子類調用這個相同的函數就會產生多義性,編譯就不能通過:
class base1{ public:virtual void fun1(){ cout << "1" << endl; } }; class base2{ public:virtual void fun1(){ cout << "2" << endl; } }; class base3{ public:virtual void fun1(){ cout << "3" << endl; } };class derive :public base1, public base2, public base3{ };int main(){derive a;a.fun1(); //fun1不明確return 0; }解決方法可以是在子類中重寫這個函數,這樣就會調用子類的函數,不會產生多義
class base1{ public:virtual void fun1(){ cout << "1" << endl; } }; class base2{ public:virtual void fun1(){ cout << "2" << endl; } }; class base3{ public:virtual void fun1(){ cout << "3" << endl; } };class derive :public base1, public base2, public base3{ public:virtual void fun1(){ cout << "derive" << endl; } };int main(){derive a;a.fun1();return 0; }?
總結
以上是生活随笔為你收集整理的C++ 多继承中的多义性的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 计算机英语一级考试试题,全国计算机一级考
- 下一篇: matplotlib调整图例的位置