Я возился с классами С++, когда столкнулся с проблемой. Я пытаюсь сделать так, чтобы класс игрока наследовался от класса 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(float x, float y, const char* name)
: Entity(x,y)
{
Name = name;
}
Вам нужно будет указать аргументы конструктора базового класса в списке инициализаторов подкласса:
Player(char const* name, double, x, double y): Entity(x, y), name(name) {}
. Я обнаружил, что большинство конструкторов, которые я пишу, имеют пустое тело, и все инициализируется из списка инициализаторов.