C++ 类继承顺序

标签 c++ class inheritance

这与我确定的其他问题类似,我通读过。我正在尝试编写一个移动类。我需要一个 Player 类和一个继承 move 类的 Item 类,反之亦然。这就是我遇到的困难。我无法全神贯注或开始工作,因为基类不是“移动”。我迷路了...

class Player {

protected:
    int x;
    int y;
    int str;
    int speed;
    int level;
    int exp;

public:
    Player(int _str, int _speed, int _level, int _exp) { x=0;y=0;str=_str;speed=_speed;level=_level;exp=_exp; }
    int GetX() {return x;}
    int GetY() {return y;}
    int GetStr() {return str;}
    int GetSpeed() {return speed;}
    int GetLevel() {return level;}
    int GetExp() {return exp;}

};


class Move : public Player {
public:
    void TryMove(int n) { x += n; }
};


int main(int argc, char *argv[])
{
Player You(101, 5, 3, 43625);


//You.TryMove(5); how?


}

TryMove(5) 失败。如果我以另一种方式进行,那么他们键入的是 Move (?),这听起来根本不对……

最佳答案

我推荐的思考方式是 Is AHas A 习语。所以... Player 是移动吗?可能不是,是 Move A Player 吗?也可能不是。然后让我们试试 Has A。移动有玩家还是玩家有移动?我会说玩家个人有一个举动。这意味着不使用继承,而是让播放器包含 Move 类的实例。所以……

class Player{
public:
    Move myMove;//where move is defined already as whatever you need it to be.    
};

//then your main
int main(int argc, const char** argv){
    //...other setup here
    Player p;
    p.myMove.TryMove(10);
    //whatever else...
}

这就是我处理您的设计的方式。至于错误...在上面的代码中,您从 Player 继承了 Move 但您创建了一个 Player 并期望它具有Move 的功能,但它无法根据您在示例代码中设置的继承来获得该功能。

如果您需要对我所说的内容或其他内容进行任何澄清,请告诉我。祝你好运

编辑:

根据您的评论,我建议您使用包装函数来获取您需要的值。

class Player{
public:
    void TryMove(int i);
private:
    Move myMove;
    int x;//the value you will be getting from Move::tryMove
};

void Player::TryMove(int i){
    this->x = myMove.tryMove(i);//store the value of the function call
    //the function obviously won't be a void function in this case
}

还有其他方法可以做到这一点,但这种方法很简单。如果您打算使用继承来解决您的问题,我会让 Player 继承自 Move,但我仍然坚持我原来的答案,我只是想帮助进一步解释。

关于C++ 类继承顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24113312/

相关文章:

c++ - 在两行之间检测 visual studio c++ 中的内存泄漏

c++ - C2296 : '|' : illegal, 左操作数的类型为 'float'

c++ - 成员包含其他继承类的继承类?

java - 父类和实现接口(interface)中同名的静态和非静态方法

python - Django 继承和永久链接

c# - 如何在 C# 中使用 Private Inheritance aka C++ 以及为什么它不存在于 C# 中

c++ - 安全赋值和复制交换习语

c++ - cmake:链接 STATIC IMPORTED 库失败

c++ - 如何使用不同的文件初始化具有重载构造函数的对象

java - 读入两个文件并逐行比较