C++继承构造函数问题
C++ inheritance constructor problems
我已经创建了两个类(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;
}
因为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';
}
相关文章:
- C++LinkedList问题.数据类型之间存在冲突?没有匹配的构造函数
- constexpr构造函数需要常量成员函数时出现问题
- 有关 c++ 构造函数的问题
- 关于复制构造函数的一个棘手问题
- 复制构造函数隐式转换问题
- 构造函数 (C++) 中的 char 指针参数存在问题
- C++:关于使用 Stroustrup 示例移动构造函数/赋值的问题
- 关于 std::bitset 构造函数的几个问题?
- 构造函数和 G++ 编译配方的问题
- 在 boost::variant 中类 holden 的复制构造函数存在问题
- C++ 关于两个类构造函数的问题
- 在构造函数 c++ 中初始化属性时出现问题
- 空构造函数和值传递问题
- 我是否需要在虚拟继承类的构造函数中初始化基类以解决菱形继承问题?
- 复制和赋值构造函数的问题
- 变分模板递归构造函数问题
- C++中用户定义的构造函数出现问题
- C ++回测问题:如何检查构造函数在假定失败时是否失败(给定输入的无效参数)
- C++的抽象类继承和构造函数的问题
- 错误 C2280 / 在 std::vector 中实例化对象时复制构造函数出现问题?