[英]C++ Non-changing member variables with sub-class specific values
My Class Hierarchy is thus: BaseClass (is an abstract class) then it has three subclasses that inherit from it: ArcaneWarrior, Guardian, Magi. 因此,我的类层次结构是:BaseClass(是一个抽象类)然后它有三个继承自它的子类:ArcaneWarrior,Guardian,Magi。
I want to have two non-changing values for DefaultHealth and DefaultMana that are specific to each subclass as they will all have different values for both variables. 我想为DefaultHealth和DefaultMana提供两个特定于每个子类的非变化值,因为它们对于两个变量都具有不同的值。
I guess I'm just looking for the best/most efficient way to do this. 我想我只是在寻找最好/最有效的方法来做到这一点。
Should I just have two virtual functions in the base class to return DefaultHealth and DefaultMana, and in the subclasses hard code in the values I want? 我应该只在基类中有两个虚函数来返回DefaultHealth和DefaultMana,而在子类中我想要的值是硬代码吗?
I appreciate any insight 我很欣赏任何见解
My vote goes to const
values in the base class and a protected
constructor: 我的投票转到基类中的
const
值和protected
构造函数:
class BaseClass{
const unsigned default_health;
const unsigned default_mana;
protected:
BaseClass(unsigned def_hp, unsigned def_mp)
: default_health(def_hp)
, default_mana(def_mp)
{
}
public:
// your functions...
};
class ArcaneWarrior
: public BaseClass
{
public:
ArcaneWarrior()
: BaseClass(200, 50)
{
}
// ...
};
This is superior to the virtual
function approach in 2 ways: 这在两个方面优于
virtual
函数方法:
const
-ness (those values can't be changed, ever) const
-ness(这些值无法更改,永远) Virtual functions don't give you const
-ness, see this example: 虚函数不提供
const
-ness,请参阅此示例:
class BaseClass{
public:
virtual unsigned GetDefaultHealth() const = 0;
virtual unsigned GetDefaultMana() const = 0;
// ...
};
class ArcaneWarrior
: public BaseClass
{
unsigned default_health, default_mana;
public:
virtual unsigned GetDefaultHealth() const{
return default_health;
}
virtual unsigned GetDefaultHealth() const{
return default_mana;
}
void SetDefaults(unsigned health, unsigned mana){
default_health = health;
default_mana = mana;
}
};
Yes, that's really the best and most straightforward way to do it. 是的,这确实是最好,最直接的方式。 With virtual functions, you get both the "non-changing"-ness you want, along with being able to determine that value through a pointer (or reference) to the base class without knowing the exact type.
使用虚函数,您既可以获得所需的“不变”,又可以通过指向基类的指针(或引用)来确定该值,而无需知道确切的类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.