从子类中的基类添加构造函数
Posted
技术标签:
【中文标题】从子类中的基类添加构造函数【英文标题】:Add upon constructor from base class in subclass 【发布时间】:2020-12-24 20:34:24 【问题描述】:当我遇到问题时,我正在处理 c++ 类。我试图让一个玩家类继承自 Entity 类并混合它们的构造函数。实体类有一个构造函数,要求您提供 x 位置浮动和 y 位置浮动。我希望 Player 类也需要 x 和 y 位置,但我也希望名称是必需的。我该怎么做?
这是我的代码:
#include <iostream>
class Entity
public:
float x, y;
int health = 30;
Entity(float X, float Y)
std::cout << "Entity Constructed!" << std::endl;
x = X;
y = Y;
~Entity()
std::cout << "Entity Destructed!" << std::endl;
void Print()
std::cout << x << ", " << y << std::endl;
void Move(float mx, float my)
x+=mx;
y+=my;
;
class Player : public Entity
public:
const char* Name;
int attack_damage = 5;
Player(const char* name)
Name = name;
void Attack(Entity& entity)
entity.health-=attack_damage;
;
int main()
Entity e(0.0f, 0.0f);
Player p(0.0f,0.0f);
std::cout << e.health << std::endl;
p.Attack(e);
std::cout << e.health << std::endl;
std::cin.get();
这是我在尝试编译上面提供的代码时收到的错误消息:
FAILED: CMakeFiles/learning-cpp.dir/src/main.cpp.o
/usr/bin/c++ -Wall -Werror -std=c++14 -g -MD -MT CMakeFiles/learning-cpp.dir/src/main.cpp.o -MF CMakeFiles/learning-cpp.dir/src/main.cpp.o.d -o CMakeFiles/learning-cpp.dir/src/main.cpp.o -c src/main.cpp
src/main.cpp: In constructor ‘Player::Player(const char*)’:
src/main.cpp:33:29: error: no matching function for call to ‘Entity::Entity()’
Player(const char* name)
^
src/main.cpp:8:5: note: candidate: ‘Entity::Entity(float, float)’
Entity(float X, float Y)
^~~~~~
src/main.cpp:8:5: note: candidate expects 2 arguments, 0 provided
src/main.cpp:3:7: note: candidate: ‘constexpr Entity::Entity(const Entity&)’
class Entity
^~~~~~
src/main.cpp:3:7: note: candidate expects 1 argument, 0 provided
src/main.cpp: In function ‘int main()’:
src/main.cpp:44:23: error: no matching function for call to ‘Player::Player(float, float)’
Player p(0.0f,0.0f);
^
src/main.cpp:33:5: note: candidate: ‘Player::Player(const char*)’
Player(const char* name)
^~~~~~
src/main.cpp:33:5: note: candidate expects 1 argument, 2 provided
src/main.cpp:28:7: note: candidate: ‘constexpr Player::Player(const Player&)’
class Player : public Entity
^~~~~~
src/main.cpp:28:7: note: candidate expects 1 argument, 2 provided
src/main.cpp:28:7: note: candidate: ‘constexpr Player::Player(Player&&)’
src/main.cpp:28:7: note: candidate expects 1 argument, 2 provided
ninja: build stopped: subcommand failed.
【问题讨论】:
您需要在子类的初始化列表中提供基类的构造函数参数:Player(char const* name, double, x, double y): Entity(x, y), name(name)
。我发现我编写的大多数构造函数的主体都是空的,并且所有内容都从初始化列表中初始化。
啊,谢谢!我能够编辑它来工作。 :)
【参考方案1】:
试试这个
Player(float x, float y, const char* name)
: Entity(x,y)
Name = name;
【讨论】:
以上是关于从子类中的基类添加构造函数的主要内容,如果未能解决你的问题,请参考以下文章
C++中如何在子类的构造函数中调用基类的构造函数来初始化基类成员变量