所以我是 C++ 的初学者,我正在使用一个名为 VBot 的抽象类,我在其中继承到其他机器人类。现在我知道我需要覆盖 VBot 类中的纯虚拟代码,所以我认为这不是问题所在。我认为因为我对 C++ 缺乏经验,所以我在构造函数上做错了一些事情,因为我不断得到无法实例化抽象类。这是 VBot.h 文件
class VBot
{
public:
VBot( int startX, int startY, Panel ^ drawingPanel ) :
x(startX), y(startY), panel(drawingPanel), energy(100), image(NULL) { };
virtual ~VBot() { };
virtual void Move() = 0;
virtual int EnergyToFightWith() = 0;
bool IsDead() const { return energy <= 0; }
virtual void Show();
bool CollidedWith ( VBot * b ) const;
void DoBattleWith ( VBot * b );
protected:
int x, y; // Current position of the VBot
gcroot<Drawing::Bitmap ^> image; // Image displayed for the VBot
gcroot<Panel ^> panel; // Panel on which to show the VBot.
int energy // Current energy of the VBot
};
class CNNBot : public VBot
{
public:
CNNBot( int startX, int startY, Panel ^ drawingPanel ){
VBot::VBot(startX,startY,drawingPanel);
image = gcnew Drawing::Bitmap("HappyBot.bmp");}
~CNNBot(){};
void Move();
int EnergyToFightWith();
bool IsDead() { return (VBot::IsDead()); }
virtual void Show() { VBot::Show();}
bool CollidedWith ( VBot * b ) { return VBot::CollidedWith(b);}
void DoBattleWith ( VBot * b ){ VBot::DoBattleWith(b);}
private:
static const int MOVE_VAL = 55;
static const int RIGHT_BOUND = 490;
static const int DOWN = 40;
static const int MAXY = 379;
bool switcher;
};
这将是 VBot.cpp
#include "stdafx.h"
#include "Vbot.h"
void VBot::Show()
{
Graphics ^ g = panel->CreateGraphics();
g->DrawImageUnscaled( image, x, y );
g->~Graphics();
}
bool VBot::CollidedWith ( VBot * b ) const
{
if ( b == NULL )
return false;
return ( x + image->Width ) >= b->x
&& ( b->x + b->image->Width ) >= x
&& ( y + image->Height ) >= b->y
&& ( b->y + b->image->Height ) >= y;
}
void VBot::DoBattleWith ( VBot * b )
{
int mine = EnergyToFightWith();
int yours = b->EnergyToFightWith();
if( mine == yours )
{
energy = energy - mine / 2;
b->energy = b->energy - yours / 2;
}
else if ( mine > yours )
{
if ( b->energy > 1 )
{
b->energy = b->energy - yours;
energy = energy + yours / 2;
}
else
{
b->energy = b->energy - 1;
energy = energy + 1;
}
}
else
{
if ( energy > 1 )
{
energy = energy - mine;
b->energy = b->energy + mine / 2;
}
else
{
b->energy = b->energy + 1;
energy = energy - 1;
}
}
}
int CNNBot::EnergyToFightWith()
{
return this->energy;
}
所以错误是无法实例化抽象类,所以我认为它正在尝试构建 VBot 而不是 CNNBot,因为在输出中它给了我 void VBot::Move(void)' : is abstract 和 'int VBot::EnergyToFightWith( void)' : 是抽象的
抱歉,我忘记在此处添加该部分是 Move()
void CNNBot::Move()
{
if (this->switcher)
{
this->x += MOVE_VAL;
if( this->x >= RIGHT_BOUND)
{
this->x = 0;
this->y += DOWN;
if(this->y > MAXY)
{
this->switcher = false;
this->y = MAXY;
}
}
}
else
{
this->x += MOVE_VAL;
if( this->x >= RIGHT_BOUND)
{
this->x = 0;
this->y -= DOWN;
if(this->y < 0)
{
this->switcher = true;
this->y = 0;
}
}
}
panel->Invalidate();
}
无论你们能提供什么帮助,都会非常感谢这位新手程序员。