在子类中具有不同值的静态基类属性
问题描述:
我有不同的可生成对象。每种对象类型都有不同的成本。我想检查用户是否可以在创建它之前负担特定对象之前。下面的方法不尊重这个要求:在子类中具有不同值的静态基类属性
class Costs {
public:
int oneCost, anotherCostAttribute; // Actual values for both attribute may differ for the objects
}
class Object {
public:
virtual Costs getCosts() = 0;
}
class Object_A : public Object {
// implement getCosts (always the same for all A's)
}
class Object_B : public Object {
// implement getCosts (always the same for all B's)
}
// Usage:
// I would have to create a specific object just to check the costs:
Object* pObj = new Object_A();
if(avilableResources >= pObj->getCosts()) {
// Store object, otherwise delete it
}
我的第二个想法是某种基类的它提供了一个虚拟的静态函数,但是这是不可能的C++:
class Object {
public:
virtual static Costs getCosts() = 0;
}
只使用一个静态成本属性不会允许辨别子类费用:
class Object {
public:
static Costs m_costs; // All objects (A,B,...) would cost the same
}
什么将directl有道Ÿ将成本与物品相关联?
答
你可以通过模板提供以下信息:
template <typename CostsT>
struct Object {
static CostsT m_costs;
};
例如,你可以有一个基Costs
类:
struct Costs {
virtual int oneCost() = 0;
virtual int anotherCost() = 0;
};
你特定类型的Costs
子类中声明你的对象:
struct Costs_A: Costs {
virtual int oneCost() override { return 1; }
virtual int anotherCost() override { return 2; }
};
using Object_A = Object<Costs_A>;
这样你可以ret在决定是否实例化Object_A之前删除特定的Costs实例:
Costs costsA = Object_A::m_costs;
答
静态函数不能是虚拟的,但仍可以被重写。简单地说,使用的版本不取决于对象的实际类,而仅取决于用于访问它的指针的声明类。
但是,这可以用来做一个测试创建一个对象之前:
class ObjectA: public Object {
...
public:
static int getCost() {
return 10;
}
...
};
class ObjectB: public Object {
...
public:
static int getCost() {
return 20;
}
...
};
然后:
Object *pObj;
if (availableResources >= ObjectA::getCost()) { // correctly calls the expected function
pObj = new ObjectA();
}
你必须只知道pObj->getCost()
将independantly返回实际类的Object
版本 - 如果您尝试使用它,甚至不会在Object
类中声明getCost
以引发编译时错误。
您的getCosts()函数是否可以访问Object或其子项中的其他成员?或者它只是Costs会员的吸气剂? – SideLobe
这只是一个吸气者,基本上是一些有整数的类,请参阅我刚添加的编辑 – Anonymous