Ошибка наследования C ++ - PullRequest
0 голосов
/ 22 марта 2011

Вот код, который вызывает ошибку (Player.cpp):

#include "Library.h"

Player::Player(){
    //generate player stats
    str = rand()%6+1+1;
    inte = rand()%6+1;
    c = (rand()%6+1)+floor(str/3);
    wis = rand()%6+1+floor(inte/4);
    ref = rand()%6+1+floor(wis/4);
    i = floor(ref/3);
    hp = floor((str+(wis/3)+(ref/2)));
    xp = 0;
}

//printStats (constant Player player reference)
//prints player's stats
void Player::printStats() const{
    cout << "\nSTR: " << str << endl;
    cout << "INTE: " << inte << endl;
    cout << "C: " << c << endl;
    cout << "WIS: " << wis << endl;
    cout << "REF: " << ref << endl;
    cout << "I: " << i << endl;
    cout << "HP: " << hp << endl;
    cout << "XP: " << xp << endl;
    cout << "Gold: " << gold << endl;
    cout << "Level: " << lvl << endl << endl;
}

int Player::giveOptions(int amount,string op1, string op2, string op3, string op4, string op5){
    cout << "Type the number then press the enter key to choose or type 'help' for extra commands." << endl;
    for(int i=1;i<=amount;i++){
        string s;
        switch(i){
        case 1:
            s = op1;
            break;
        case 2:
            s = op2;
            break;
        case 3:
            s = op3;
            break;
        case 4:
            s = op4;
            break;
        case 5:
            s = op5;
            break;
        }
        cout << i << ". " << s << endl;
    }
    while(true){
        string s;
        cin >> s;
        if (s == "1")
            return 1;
        else if (s == "2")
            return 2;
        else if (s == "3")
            return 3;
        else if (s == "4")
            return 4;
        else if (s == "5")
            return 5;
        else{
            if (s == "stats")
                printStats();
            else if (s == "help"){
                cout << "Type the number that is next to the option you wish to choose then press the enter key, or 'stats' to print all of your stats." << endl;
                cout << "E.G:\n1. Town\nI want to go to the town\n1" << endl;
            }
            else
                cout << "Command not recognised. If you're confused, type 'help'." << endl;
        }

    }
}

(оригинальный вопрос ниже)

Я довольно прост в C ++,и я не уверен, почему это приводит к ошибке.В Player.cpp все члены Entity, которые, по моему мнению, были унаследованы, выдают ошибку «x не является членом Player».Я думал только о том, что неправильно использую наследование.

Entity.h:

#include "Library.h"

using namespace std;
class Entity {
public:
    void printStats() const;
protected:
    //player stats
    std::string name;
    double str;     //strength
    double wis;     //wisdom
    double ref;     //reflex
    double hp;      //health points
    double i;       //initiative
    double inte;    //intelligence
    double c;       //courage
    int gold;       //gold
    int xp;         //experience
    int ap;         //armour points
    int wd;         //weapon damage
    int lvl;        //level
    int sp;         //skill points
};

Player.h

#include "Library.h"

using namespace std;

class Player: public Entity{
public:
    Player();
    int giveOptions(int amount, string op1, string op2, string op3, string op4, string op5);
};

Ответы [ 2 ]

4 голосов
/ 22 марта 2011
void Player::printStats() const

Должно быть, в соответствии с вашими заголовками:

void Entity::printStats() const

На включениях выполните одно из следующих действий, в зависимости от того, что подходит вашему коду:

1.

  • Player.h должен включать Entity.h
  • Library.h должен не включать Player.h или Entity.h
  • Player.h и / илиEntity.h может включать Library.h, если действительно необходимо.

или 2.

  • Player.h должно включать Entity.h, но не Library.h
  • Entity.h обязательно не включает Library.h
  • Library.h может включать Player.h и / или Entity.h

Это позволяет избежать циклических зависимостей, которые у вас есть в настоящее время - что приводит к определению Player до Entity и возникновению ошибки base class undefined.

0 голосов
/ 22 марта 2011

Поскольку компилятор жалуется - ни класс Entity, ни Player не имеют переменной-члена с именем x.Вам необходимо включить "Entity.h" в заголовочный файл Player, так как в текущем переводчике единицы измерения не знает, что такое Player.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...