2011-06-27 32 views
7
class A { 
    public: 
     void fa() { 
     } 
    }; 

class B : public A{ 
public: 
    void fb() { 
    } 
}; 

class C : public A, public B { 
public: 
    void fc() { 
     //call A::fa(), not B::A::fa(); 
    } 
}; 

如何從C::fc()函數調用A::fa()函數。從派生類中引用基類成員

GCC使用direct base A inaccessible in C due to ambiguity發出警告,這是否意味着沒有直接的方法來引用基類成員?

+0

在您的本次代碼'類B'不繼承'類A'。你已經把更新的代碼? – iammilind

+0

我的錯誤:) ,現在它是固定的 – MKo

+1

你想要有一個'A'的基類子對象爲'C'或兩個'A'基類子對象(一個來自'A'的'C'和一個來自'B'的派生自'A')?現在你有兩個,這可能也可能不是你的意圖。 –

回答

0

您可以使用virtual繼承來解決這樣的問題:現在

class B : virtual public A { 

,您可以使用A::fa()只需在孩子class C

void fc() 
{ 
    fa(); 
} 

不過,我一般看不到任何實際需要再繼承class Aclass C,當B已經public盟友繼承A。所以,在你的情況,你可以把它簡單:

class C : public B { 

編輯

如果你想爲A 2個實例。然後您打算直接實例可以製成的C的對象:

class C : public B { 
    A obj; 

因爲,具有直接繼承A不會在反正可用。您不能在C範圍內聲明任何指針或引用它。

+0

這不是實際使用,我只是想知道有沒有辦法做到這一點?順便說一下,在虛擬繼承的情況下,將會有一個基類,並且不會有任何歧義。 – MKo

+0

@MKo,我已經在我編輯的答案中提到過。對於你的情況,你不需要將'A'繼承到'C'。從長遠來看,這也可能是一個糟糕的設計。 – iammilind

1

我剛剛編譯你的代碼codepad.org,把A::fa()就足以從你的C::fc()函數中調用fa()。

void fc() { 
     A::fa(); 
    } 

以下是使用您的代碼與鍵盤的鏈接。

http://codepad.org/NMFTFRnt

+0

我不知道什麼編譯器鍵盤使用,但鏗鏘3.0/133044和g ++ 4.5.1都拒絕。 –

+0

@James McNellis:是的,它更多地涉及**編譯器問題**而不是語言本身。 – Jhaliya

+0

它編譯是因爲'B'不是從代碼中的'A'派生的。 –

8

一種選擇是創建一個可用於鑄造到正確的基類子對象短線類別:

struct A { 
    void fa() { } 
}; 

struct B : A { 
    void fb() { } 
}; 

// Use a stub class that we can cast through: 
struct A_ : A { }; 

struct C : A_, B { 
    void fc() { 
     implicit_cast<A_&>(*this).fa(); 
    } 
}; 

implicit_cast被定義爲:

template <typename T> struct identity { typedef T type; } 

template <typename T> 
T implicit_cast(typename identity<T>::type& x) { return x; } 
+0

我承認,我我被這個問題困住了,而且對於是否有一種方法可以在不向網格中注入存根類的情況下非常感興趣。 –

+0

使用存根是一個很好的解決方法,我認爲沒有任何方法可以在沒有這種技巧的情況下實現這種行爲。這是我從未考慮的語言的限制! –

+0

爲什麼你使用'implicit_cast'而不是'static_cast'?我找到一個SO帖子回答我的問題,但你可以添加一些解釋,或鏈接到一些信息。 –

0

我不認爲你可以做你想做的事。這裏有一個不明確的地方:當你說A::fa()時,它仍然不會告訴編譯器哪個對象使用哪個對象。沒有任何方法可以訪問類A。這就是警告告訴你的。

雖然這似乎是一個非常奇怪的構造。公共繼承應該用於關係。你是說C是-兩次?這沒有意義。這表明這是一個在實踐中永遠不會出現的人爲的例子,或者你應該重新考慮這個設計。

5

我剛剛從ISO C++ 2003標準(10.1。3)

A class shall not be specified as a direct base class of a derived class more than once. [Note: a class can be 
an indirect base class more than once and can be a direct and an indirect base class. There are limited 
things that can be done with such a class. The non-static data members and member functions of the direct 
base class cannot be referred to in the scope of the derived class. However, the static members, enumerations 
and types can be unambiguously referred to. 

這意味着沒有直接的方法:(

相關問題