2011-04-30 66 views
19

我得到这个错误,但我想我只会得到它,如果成员的保护水平过高,并使其无法访问,但我发现了也无妨。错误:函数是无法访问

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 

Weapon.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' 是无法访问”

回答

56

你想公有继承:

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++教科书是你学习?

+0

我没有使用教科书,只是从互联网上的地方拿起零散的东西。 – pighead10 2014-06-20 15:03:59

11

继承必须是public:

class Weapon : public Shopable 
8

您正在使用私有继承:

class Weapon : Shopable 

因此,事实上,一个武器是Shopable不是其他类可见。将其更改为公有继承:

class Weapon : public Shopable 
+0

是不是隐含继承'protected'? – 2011-04-30 21:05:15

+4

@Gustav:不,它是'struct'公开的,'class'是私有的。 – 2011-04-30 21:08:09

+0

@Mike我必须检查,因为我很好奇,而且你是对的。 – 2011-04-30 21:38:47

4

通过不指定任何其他内容即可获得私有继承。试试这个

class Weapon : public Shopable{ 
5

class ES默认为私有继承,struct s到公众。您使用class,所以你需要使用: public Base如果你想模式 “是一个”:

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