【发布时间】:2010-12-08 03:02:11
【问题描述】:
我正在尝试为游戏设计一个武器类。这是我为满足我的需要而编写的一些代码:
class weapon {
public:
int fireRate;
int bulletDamage;
int range;
ofImage sprite;
ofImage bulletSprite;
bullet bullets[50];
int activeBullet;
public:
void fire();
};
class machineGun: public weapon {
public:
void fire();
};
class flamer: public weapon {
public:
void fire();
};
然后我想像这样定义一个武器数组:
//Weapon variables
const int totalWeapons = 2;
int currentWeapon = 1;
weapon weapons[totalWeapons];
我希望元素 [0] 代表 machineGun 类,元素 [1] 代表火焰喷射器类。我是否以正确的方式解决这个问题?我应该以某种方式重构它吗?我如何实现拥有这两种不同武器的阵列?
我的想法是,当我调用 weapons[0].fire(); 时,我得到一个 machineGun 类,当我调用 weapons[1].fire(); 时,我得到火焰喷射器。
编辑:感谢大家的帮助。我在使用“weapons[0] = new machineGun;”时遇到了一些问题。当我尝试运行此代码时,出现错误“无法分配常量大小为 0 的数组”。
有没有人知道为什么这不起作用?我更新后的代码如下所示:
//Weapon variables
const int totalWeapons = 2;
int currentWeapon = 1;
weapon weapons[totalWeapons];
weapons[0] = new machineGun;
weapons[1] = new flamer;
但我得到了很多错误:
1>gameplay.cpp(49) : error C2466: cannot allocate an array of constant size 0
1>gameplay.cpp(49) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>gameplay.cpp(49) : error C2371: 'weapons' : redefinition; different basic types
1> gameplay.cpp(48) : see declaration of 'weapons'
1>gameplay.cpp(49) : error C2440: 'initializing' : cannot convert from 'machineGun *' to 'int []'
1> There are no conversions to array types, although there are conversions to references or pointers to arrays
1>gameplay.cpp(50) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>gameplay.cpp(50) : error C2369: 'weapons' : redefinition; different subscripts
1> gameplay.cpp(48) : see declaration of 'weapons'
1>gameplay.cpp(50) : error C2440: 'initializing' : cannot convert from 'flamer *' to 'int [1]'
1> There are no conversions to array types, although there are conversions to references or pointers to arrays
我采取了另一种不同的方法并得到了一些不同的错误。我仍然很不确定这一切是如何粘合在一起的。
//Weapon variables
const int totalWeapons = 2;
int currentWeapon = 1;
weapon weapons[totalWeapons] = {new machineGun, new flamer};
有错误:
1>gameplay.cpp(48) : error C2275: 'machineGun' : illegal use of this type as an expression
1> gameplay.h(36) : see declaration of 'machineGun'
1>gameplay.cpp(48) : error C2275: 'flamer' : illegal use of this type as an expression
1> gameplay.h(41) : see declaration of 'flamer'
答案最终是这样的:
//Weapon variables
const int totalWeapons = 2;
int currentWeapon = 1;
weapon *weapons[totalWeapons] = {new machineGun, new flamer};
感谢所有帮助我解决这个问题的人!
【问题讨论】:
-
如果您只是计划拥有固定数量的武器类型,这很好;然后你会有类似
weapons[0] = new machineGun; weapons[1] = new flamer; -
你声明了一系列武器,你的机关枪和喷火器都是武器。这不行吗?
-
@isbadawi,你能看一下我的编辑吗,我似乎无法正常工作。
标签: c++ polymorphism