我刚从java转到c ++,我真的很挣扎曾经的基本概念。我想做的就是创建一个名为'Spaceship'的抽象类,给它一个带有4个参数的构造函数,然后在一个名为'Alienspaceship'的子类中,我想创建一个带有5个参数但继承'太空飞船'的构造函数'构造者前4个论点。我一直在寻找这个地方,似乎无法找到我正在寻找的东西。以下是我的代码。请感谢能帮助我的人!
头
#ifndef SPACESHIP
#define SPACESHIP
#include "Enum.h"
class Spaceship{
public:
float health;
float food;
float cash;
float misc;
public:
Spaceship(float, float, float, float);
};
class AlienSpaceship: public Spaceship{
OrganismType race;
public:
AlienSpaceship(float, float, float, float, OrganismType):Spaceship(float, float, float, float){}
};
#endif
CPP
#include "Spaceship.h"
Spaceship::Spaceship(float health, float food, float cash, float misc){
this->health = health;
this->food = food;
this->cash = cash;
this->misc = misc;
}
AlienSpaceship::AlienSpaceship(float health, float food, float cash, float misc, OrganismType race):Spaceship(health, food, cash, misc){
this->race = race;
}
您似乎误解了构造函数初始化列表的工作原理。
它用在构造函数的定义(即实现)中,构造函数的声明不需要它。
事实上,你在AlienSpaceship
类中的当前声明实际上定义(实现)构造函数,因为结束{}
。
因此,对于课程,您需要做的就是
class AlienSpaceship: public Spaceship{
...
public:
AlienSpaceship(float, float, float, float, OrganismType);
};
在相关的说明中,我建议您使用初始化列表来初始化成员变量,然后您的构造函数可能只是
Spaceship::Spaceship(float health, float food, float cash, float misc)
: health(health), food(food), cash(cash), misc(misc)
{ /* Empty */ }
AlienSpaceship::AlienSpaceship(float health, float food, float cash, float misc, OrganismType race)
: Spaceship(health, food, cash, misc), race(race)
{ /* Empty */ }
当然,这可以在类定义本身在线完成:
class AlienSpaceship: public Spaceship{
...
public:
AlienSpaceship(float health, float food, float cash, float misc, OrganismType race)
: Spaceship(health, food, cash, misc), race(race)
{ /* Empty */ }
};
AlienSpaceship(float, float, float, float, OrganismType):Spaceship(float, float, float, float){}
应该只是:
AlienSpaceship(float, float, float, float, OrganismType);
在你的标题中。您实际上已在标题中创建了第二个实现...
你应该只有每个类成员的一个定义,但你有两个
第一个(隐含在类定义中)
public:
AlienSpaceship(float, float, float, float, OrganismType):Spaceship(float, float, float, float)
{}
第二个在源文件
AlienSpaceship::AlienSpaceship(float health, float food, float cash, float misc, OrganismType race):Spaceship(health, food, cash, misc)
{
this->race = race;
}
选择其中之一,或者说
AlienSpaceship(float health, float food, float cash, float misc, OrganismType race):Spaceship(health, food, cash, misc)
{
this->race = race;
}
进入类定义
要么在课堂上宣布
class AlienSpaceship: public Spaceship{
OrganismType race;
public:
AlienSpaceship(float, float, float, float, OrganismType);
并在源文件中定义
AlienSpaceship::AlienSpaceship(float health, float food, float cash, float misc, OrganismType race):Spaceship(health, food, cash, misc)
{
this->race = race;
}
还有,像这样的声明
AlienSpaceship(float, float, float, float, OrganismType):Spaceship(float, float, float, float)
is incorrect too. Actually, it conatains a part of defenition.