【发布时间】:2011-05-12 14:34:34
【问题描述】:
我正在创建一个涉及继承的非常简单的程序。我将一个函数放入父类的“受保护”区域,现在我无法从子类访问。这是我的代码:
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 在 Game 中是私有的。前面不应该有“public:”吗?
-
请停止使用动词“throw”来表示编译时错误。 Throw 是一个 C++ 关键字,用于引发异常,仅在运行时发生。
-
另外,受保护的继承是怎么回事?甚至 Bjarne Stroustrup 在“C++ 编程语言”中也提到它是一个他永远无法提出用例的特性。
标签: c++ inheritance derived