【发布时间】:2021-06-24 09:35:24
【问题描述】:
我创建了 2 个类(Entity 和 Player)。
所以基本上Player 类继承自Entity 类,所以Player 实例本身就是Entity 对象。
这是第一堂课:
#include <iostream>
#define print(obj) std::cout << obj << std::endl
class Entity {
public:
int xPos, yPos;
Entity(int xInitPos, int yInitPos) {
xPos = xInitPos;
yPos = yInitPos;
}
void move(int _x, int _y) {
xPos += _x;
yPos += _y;
}
};
第二类Player需要有一些额外的数据:
int healt;
int level;
这里是我困惑的部分,我不知道我是否应该为这个类指定一个新的构造函数,因为它需要获取2个额外的参数。
这是我到目前为止所做的:
class Player : public Entity {
public:
int healt;
int level;
// I know that this piece of code is wrong
Player(int _level, int _healt) {
level = _level;
healt = _healt;
}
};
我是 C++ 编程新手,我不知道继承是如何工作的,我也不知道如何创建 Player 类的实体以及它的参数是什么需要。
这里是主要功能:
int main() {
Entity ent1 = Entity(0, 0);
ent1.move(4, 8);
Player player = Player(what attributes);
return 0;
}
【问题讨论】:
-
您可以在子构造函数中调用基本构造函数,例如
Player(int _level, int _health) : Entity(0, 0), level(_level), health(_health) {}如您所见,我使用 0, 0 作为Entity构造函数。因此,如果我想指定位置,我将不得不调整我的Player构造函数以也接受x和y位置:Player(int _level, int _health, int x, int y) : Entity(x, y), level(_level), health(_health) {}
标签: c++ class object inheritance