我正在创建一个涉及继承的非常简单的程序。我将一个函数放入父类的“ 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() 函数无法访问。
这里有什么帮助吗?谢谢!!
最佳答案
您的<<
使用 const Game &
调用运算符对象,这意味着该函数只能调用 const
Game
的成员函数
添加const
至getPrice
和printGame
:
double getPrice() const {return Price;}
double printGame() const {return getPrice();}
您还必须创建 printGame
公开。
关于c++ - 派生类无法访问继承的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5979647/