问这个问题是一种遗憾,可能更适合代码审查网站,所以提前道歉。
我的问题如下(可以扩展到其他语言,因为它更面向对象):
我有一门课:
class Unit
{
public:
Unit(Type);
Type type;
private:
int weaponry;
int shielding;
int hull;
int rapid_fire;
}使用枚举在不同类型的单元之间进行区分。
enum Type{
Cruiser,
Missile
}; 所有的单位都将用一个默认值(加上一个因子,取决于外部变量)进行初始化。
Unit::Unit(Type type)
{
this->type = type;
int weaponry, shielding, hull,rapid_fire;
switch(type){
case Cruiser:
weaponry = 2700;
shielding = 50;
hull = 400;
rapid_fire = 5;
break;
case Missile:
weaponry = 200;
shielding = 20;
hull = 80;
rapid_fire = 0;
break;
}
this->weaponry = weaponry ; //+ whatever
this->shielding = shielding; //+ whatever
this->hull = hull; //+ whatever
this->rapid_fire = rapid_fire;
}我还将使用一个方法来更改对象的值,比如typical
setHull(int newHull){this->hull = newHull} 在其中一种方法中,我希望将其中一个私有变量恢复为其默认值,在本例中,如果是Cruiser this->shielding = 50,如果它是导弹= 20。
我的问题如下。我做错了什么吗?
我有几个选项来保留默认值,或者使用(我会"noobly“选择的选项)
#define initial_cruiser_shielding 50使用枚举:
enum shielding_init{
cruiser_i = 50,
missile_i = 20
};拥有基本对象的默认实例,然后只需复制它们并创建我需要的任意数量的新对象。
提前感谢!
发布于 2014-12-17 00:28:43
我的建议是创建可以返回默认值的私有静态成员函数。
class Unit
{
public:
Unit(Type);
Type type;
int set_default_weaponry()
{
weaponry = get_default_weaponry();
}
int set_default_shielding()
{
shielding = get_default_shielding();
}
int set_default_hull()
{
hull = get_default_hull();
}
int set_default_rapid_fire()
{
rapid_fire = get_default_rapid_fire();
}
private:
int weaponry;
int shielding;
int hull;
int rapid_fire;
static int get_default_weaponry();
static int get_default_shielding();
static int get_default_hull();
static int get_default_rapid_fire();
}https://stackoverflow.com/questions/27508801
复制相似问题