C++继承构造函数问题

C++ inheritance constructor problems

本文关键字:问题 构造函数 继承 C++      更新时间:2024-04-28

我已经创建了两个类(EntityPlayer(。

所以基本上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;
}

因为Entity没有不带参数的默认构造函数,所以也必须初始化它:

Player(int _level, int _healt) : Entity(0 , 0) {
level = _level;
healt = _healt;
}

或者更习惯地说:

Player(int _level, int _healt) : Entity(0 , 0), healt(_healt), level(_level) {}

在上面的例子中,我默认情况下用0初始化两个位置,如果你想自己提供位置值,你必须有一个构造函数,它也接受这些值:

Player(int _level, int _healt, int posX, int posY) 
: Entity(posX , posY), healt(_healt), level(_level) {}

并称之为:

Player player = Player(1, 100, 0, 0);

以下是它的外观示例:

#include <iostream>
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;
}
};
class Player : public Entity {
public:
int health;
int level;
// Constructor that also accepts x and y which are passed on to the base constructor
// The syntax with the : and , separated values is a initializer list.
Player(int x, int y, int _level, int _health)
: Entity(x, y)
, level(_level)
, health(_health) {}
// Constructor without x and y, passing 0 for x and y to the base constructor
Player(int _level, int _health)
: Entity(0,0)
, level(_level)
, health(_health) {}
};
int main() {
Player p(2, 3, 1, 100); // Creates a player at position (2,3) with level 1 and 100 health
Player p2(2, 110); // Creates a player at position (0,0) and level 2 and 110 health
std::cout << p.xPos << 'n';
}