Тонна ошибок, связанных с грязным кодом ООП - PullRequest
0 голосов
/ 01 мая 2011

Я получаю загружает ошибок с этим при компиляции. Надеюсь, мне станет понятнее, если я решу одну из них (если нет, то я смогу опубликовать остальные):

'Weapon' : illegal member initialization: 'Name' is not a base or member

Это имеет имя и стоимость. Оружие наследует Shopable, а Shopable имеет имя, стоимость и описание в защищенном разделе.

Shopable.h:

#ifndef _SHOPABLE_H_
#define _SHOPABLE_H_

#include "Library.h"

class Shopable{
protected:
    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 "Shopable.h"

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

#endif
Library.h:

#ifndef _LIBRARY_
#define _LIBRARY_

#include <iostream>
#include <string>
#include <cstring>
#include <cmath>
#include <cstdio>
#include <cstdarg>
#include <vector>
#include <ctime>
#include <cmath>
#include <cstdlib>
#include <map>
#include <exception>
#include <sstream>

//file includes
#include "Globals.h"
#include "Player.h"
#include "Exception.h"
#include "Weapon.h"
#include "Armour.h"
#include "Consumable.h"

//prototypes that require "Library.h"
bool Poglathon(std::vector<std::string>& text,Player *player);
bool PoglathonTown(std::vector<std::string>& text,Player *player);

std::map<std::string,Weapon*> init_weapons(void);
std::map<std::string,Armour*> init_armour(void);
std::map<std::string,Consumable*> init_consumables(void);

#endif //__LIBRARY__

Globals.h:

//global variables
#ifndef _GLOBAL_
#define _GLOBAL_

#include <vector>
#include <iostream>
#include <string>

//prototypes
void NPCTalk(std::string const& speaker,std::vector<std::string> const& text);
void wait(double seconds);
void regionChange(int amount);
int getPositionInStringVector(std::vector<std::string> const& vec,std::string value);


//variables


//defines
#define RegionChange 3

////tostring
template <class TYPE> std::string tostring(const TYPE & t ) {
    std::ostringstream os;
    os << t;
    return os.str();
};

#endif //__GLOBAL__

Ответы [ 3 ]

8 голосов
/ 01 мая 2011

Вы можете только инициализировать членов класса current в списке инициализации.NameCost) оба являются членами базового класса;они должны быть инициализированы в конструкторе базового класса.

Самый простой способ сделать это - добавить конструктор в Shopable:

class Shopable {
    ...
public:
    Shopable(std::string n, int c, std::string d)
    : Name(n), Cost(c), Description(d) {}
    ...
};

, а затем использовать его в Weapon список инициализации:

class Weapon : public Shopable {
    ...
public:
    Weapon(int c,int d,std::string n)
    : Shopable(n,c,""), Damage(d)
    {}
};
2 голосов
/ 01 мая 2011

Вы должны создать конструктор для Shopable и использовать его для инициализации унаследованных членов.

class Shopable{
protected:
    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;
public:
    Shopable(std::string n, int c, std::string d) : Name(n), Cost(c), Description(d) {}
};

и

class Weapon : public Shopable{
private:
    int Damage;
public:
    Weapon(int c,int d,std::string n) : Shopable(n, c, "Weapon"), Damage(d) {} // should probably reorder the parameters to match, just for consistency
    std::string getDesc() const{
        return getName()+"\t"+tostring(Damage)+"\t"+tostring(Cost);
    }
    int getDamage() const{return Damage;}
    int DamageTarget(Entity* target){
        int DamageDealt = 0;
        //do damage algorithm things here
        return DamageDealt;
    }
};
2 голосов
/ 01 мая 2011

В

Weapon(int c,int d,std::string n) : Cost(c), Damage(d), Name(n){}

нельзя использовать члены базового класса в списке инициализации.Вместо этого определите правильный конструктор в Shoppable и назовите его так:

Weapon(int c,int d,std::string n) : Shoppable(c, d, n)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...