2009-10-10 69 views
5

這裏的示例沒有任何意義,但這基本上是我如何使用Python編寫我的程序,現在我正在用C++重寫它。我仍然試圖在C++中掌握多重繼承,而我需要做的是從主要通過C實例訪問A :: a_print。下面你會看到我在說什麼。這可能嗎?訪問虛擬派生類的成員/方法

#include <iostream> 
using namespace std; 

class A { 
    public: 
    void a_print(const char *str) { cout << str << endl; } 
}; 

class B: virtual A { 
    public: 
    void b_print() { a_print("B"); } 
}; 

class C: virtual A, public B { 
    public: 
    void c_print() { a_print("C"); } 
}; 

int main() { 
    C c; 
    c.a_print("A"); // Doesn't work 
    c.b_print(); 
    c.c_print(); 
} 

這是編譯錯誤。

test.cpp: In function ‘int main()’: 
test.cpp:6: error: ‘void A::a_print(const char*)’ is inaccessible 
test.cpp:21: error: within this context 
test.cpp:21: error: ‘A’ is not an accessible base of ‘C’ 

回答

12

使B或C繼承自A使用「公共虛擬」而不是「虛擬」。否則,它被認爲是私人繼承的,你的main()將不會看到A的方法。

+0

賓果。就是這樣。謝謝。 – Scott 2009-10-10 21:41:01

+0

這是一個很好的觀點:足以讓兩個繼承路徑之一公開授予訪問權限。所採取的路徑是提供最多訪問權限的路徑。 – 2009-10-10 21:50:30

相關問題