2011-04-30 94 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"