c++ - 派生类无法访问继承的函数?

标签 c++ inheritance derived

我正在创建一个涉及继承的非常简单的程序。我将一个函数放入父类的“ 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的成员函数

添加constgetPriceprintGame :

double getPrice() const {return Price;}
double printGame() const {return getPrice();}

您还必须创建 printGame公开。

关于c++ - 派生类无法访问继承的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5979647/

相关文章:

c++ - 我如何接受 0 作为整数而不是 bool 值?

c++ - C++ 中的可选分号

c++ - 为什么派生*到基*之间的转换会因私有(private)继承而失败?

c - C和派生数据类型?

c++ - 在 C++11 中有零大小的 std::array 的原因吗?

C++删除文件中的文本行

Java 子类无法识别其泛型父类(super class)

Java向父类(super class)添加方法

c++ - 在派生类中重载运算符 <<

c++ - "baseclass"用于模板?