我正在創建一個涉及繼承的非常簡單的程序。我把一個函數放到父類的「protected」區域,現在我沒有從子類中訪問。這裏是我的代碼:派生類無權訪問繼承函數?
class Product : protected Item
{
private:
double Price;
protected:
double getPrice(){return Price;}
//other code not connected
};
後來,我得出:
class Toy : protected Item
{
// class Toy code that does not mention getPrice() at all
};
在這之後,我得出另一個類中,我實際上嘗試使用用getPrice()函數。
在新類的頭文件:
class Game : protected Toy
{
double printGame(){return getPrice();}
};
此行不給我一個錯誤。
但在文件game.cpp:
ostream& operator << (ostream& Output, const Game &printedGame)
{
return Output
<< "The game price is: "
//This is the problem line
<< printedGame.printGame()
<< "." ;
}
「printedGame」這個詞返回我「錯誤:對象的類型是不與成員函數兼容的限定」
當我試圖直接去(我嘗試過,因爲這樣的:)
printedGame.getPrice()
我得到這個錯誤,另外一個通知我,該用getPrice()函數是無法訪問的。
這裏有什麼幫助嗎?謝謝!!
printGame在遊戲中是私人的。在它之前不應該有「公開:」嗎? – 2011-05-12 14:40:15
請停止使用動詞「throw」編譯時錯誤。 Throw是一個C++關鍵字,用於引發異常,這隻發生在運行時。 – 2011-05-12 14:55:29
另外,受保護的繼承是什麼?即使Bjarne Stroustrup在「C++編程語言」中也提到了它作爲一個功能,他永遠不會想出一個用例。 – 2011-05-12 14:57:14