2

我正在创建一个涉及继承的非常简单的程序。我将一个函数放入父类的“受保护”区域,现在我无法从子类访问。这是我的代码:

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() 函数不可访问。

这里有什么帮助吗?谢谢!!

4

5 回答 5

4

您的<<操作员是用一个对象调用的,这意味着该函数const Game &只能调用constGame

添加constgetPriceprintGame

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

您还必须printGame公开。

于 2011-05-12T14:38:47.937 回答
0

getPrice() 方法是 Product 的成员,而不是 Item。所以从 Item 派生 Toy 不会让它访问 getPrice()。它必须派生自 Product (或其子类之一。)

于 2011-05-12T14:36:05.497 回答
0

我对此进行了尝试,但必须做出一些假设才能使其发挥作用。如所写,代码应该可以工作

#include <iostream>

using std::ostream;

// I added this to make sure it looks close to your stated problem
class Item
{
};

class Product : protected Item 
{
private:    
    double Price;
protected:   
    // getter needs to be const, for the ostream operator to work
    double getPrice() const
    {
        return Price;
    }
};

// I changed this to derive from Product, otherwise, there's no inheritance tree.
// Is this what you intended to do?
class Toy : protected Product
{
};

class Game : protected Toy
{  
    // if you don't specify an access modifier, C++ defaults to private
public:
    // getter needs to be const, for the ostream operator to work
    double printGame() const
    {
        return getPrice();
    }
};

ostream& operator << (ostream& Output, const Game &printedGame)
{
    return Output  << "The game price is: " << printedGame.printGame() << "." ;
}

int _tmain(int argc, _TCHAR* argv[])
{
    return 0;
}
于 2011-05-12T15:19:02.057 回答
0

getPrice的成员可以访问Game,但您operator<<不是成员,也不应该是成员。

相反,使用朋友声明来授予operator<<(ostream&, const Game&)访问权限。

class Product : protected Item 
{

private:

  double Price;

protected:

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

class Toy : protected Product
{
};

class Game : protected Toy
{
  friend ostream& operator<<(ostream&, const Game&);
};

ostream& operator << (ostream& Output, const Game &printedGame)
{
  return Output 

   << "The game price is: "

   //This is the problem line

   << printedGame.getPrice()

   << "." ;
}
于 2011-05-12T14:38:53.963 回答
0

getPrice() 方法是 Product 类的成员,但您从 Item 派生。

另外 - 如果你会这样称呼它,那么我相信你需要一个 const 函数来调用 Product 类

于 2011-05-12T14:40:25.000 回答