类继承:函数不可访问

新手上路,请多包涵

我收到此错误,但我认为只有在会员的保护级别太高且无法访问时才会收到此错误,但我还是收到了。

Shopable.h:

 #ifndef _SHOPABLE_H_
#define _SHOPABLE_H_

#include "Library.h"

class Shopable{
private:
    std::string Name;
    int Cost;
    std::string Description;
public:
    std::string getName() const{return Name;}
    int getCost() const {return Cost;}
    virtual std::string getDesc() const = 0;
};

#endif

武器.h:

 #ifndef _WEAPON_H_
#define _WEAPON_H_

#include "Globals.h"
#include "Shopable.h"

class Weapon : Shopable{
private:
    int Damage;
public:
    Weapon(int Cost,int Damage,std::string Name) : Cost(Cost), Damage(Damage), Name(Name){}
    std::string getDesc() const{
        return getName()+"\t"+tostring(Damage)+"\t"+tostring(Cost);
    }
    int Damage(Entity *target){
        int DamageDealt = 0;
        //do damage algorithm things here
        Special();
        return DamageDealt;
    }
};

#endif

正确的随机函数中的某些行包括:

 std::map< std::string, Weapon* > weapons;
Weapon* none = new Weapon(0,0,"None");
weapons[none->getName()] = none;

错误在于 getName() -“错误:函数 ‘Shopable::getName’ 无法访问”

原文由 pighead10 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.5k
2 个回答

你想要公共继承:

  class Weapon : Shopable

应该:

  class Weapon : public Shopable

此外,像 _SHOPABLE_H_ 这样的名称在用户编写的 C++ 代码中是非法的,因为它们是为 C++ 实现保留的。忘记前导下划线并使用 SHOPABLE_H

和:

  Weapon(int Cost,int Damage,std::string Name)

应该:

  Weapon(int Cost,int Damage, const std::string & Name )

以避免复制字符串的不必要开销。

您可能需要重新考虑您的命名约定 - 通常,C++ 中的函数参数名称以小写字母开头。以大写字母开头的名称通常保留给用户定义的类型(即类、结构、枚举等)。

有趣的是,您正在学习哪本 C++ 教科书?

原文由 user2100815 发布,翻译遵循 CC BY-SA 3.0 许可协议

class es 默认为私有继承, struct s 为 public。你正在使用 class ,所以你需要使用 : public Base 如果你想建模“is-a”:

 class Weapon : public Shopable{ // added "public"

原文由 Marc Mutz - mmutz 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题