2017-07-26 67 views
-3

我有以下的測試程序如何解決C++中的鑽石問題?

#include<iostream> 
using namespace std; 


class Faculty { 
// data members of Faculty 
public: 
    Faculty(int x) { 
    cout<<"Faculty::Faculty(int) called"<< endl; 
    } 
    void test() { 
     cout<<"Faculty::test called" << endl; 
    } 
}; 

class Student { 
// data members of Student 
public: 
    Student(int x) { 
     cout<<"Student::Student(int) called"<< endl; 
    } 
    void test() { 
     cout<<"Student::test called" << endl; 
    } 
}; 

class TA : virtual public Faculty, virtual public Student { 
public: 
    TA(int x):Student(x), Faculty(x) { 
     cout<<"TA::TA(int) called"<< endl; 
    } 
}; 

int main() { 
    TA ta1(30); 
    ta1.test(); 
} 

的錯誤,編譯

8be257447d8c26ef785b1a60f2884a.cpp: In function 'int main()': 
748be257447d8c26ef785b1a60f2884a.cpp:36:6: error: request for member 'test' is ambiguous 
    ta1.test(); 
    ^
748be257447d8c26ef785b1a60f2884a.cpp:22:7: note: candidates are: void Student::test() 
    void test() { 
    ^
748be257447d8c26ef785b1a60f2884a.cpp:11:7: note:     void Faculty::test() 
    void test() { 
    ^

中越來越即使我在這裏使用虛擬繼承。任何解決方案?

+11

這裏沒有鑽石。你只是從兩個不相關的基類中發生名字衝突,而虛擬繼承對此無能爲力。不要把你不明白的解決方案扔給無關的問題。 –

+0

有關於此的任何解決方案? – BSalunke

+2

嘗試使用'ta1.Student :: test()'或'ta1.Faculty :: test()' – GAVD

回答

2

此處不需要關鍵字virtual,類StudentFaculty通過繼承常見類無關。

如果要在TA中使用特定方法,可以將using Student::test;using Faculty::test;放入TA類聲明中。

我希望這個例子從純粹的教育目的出現,因爲如果它的使用/計劃於實際應用中使用 - 這是某事物的標誌是怎麼回事錯設計:)

0

您只需兩個test()方法你的TA類,一個從Faculty繼承,另一個從Student,編譯器正確地通知你它不能決定你想調用哪一個。

您需要解決,要麼說明確要調用的方法。

TA ta1(30); 
ta1.Faculty::test(); 

或對象如何應及時治療(這將意味着該調用哪個方法):

((Faculty &)ta1).test();