【发布时间】:2017-06-14 08:57:08
【问题描述】:
我有不同的对象可以生产。每种对象类型都有不同的成本。我想检查用户是否能负担得起BEFORE创建它的特定对象。以下方法不遵守此要求:
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;
}
仅使用静态 Costs 属性将无法区分子类成本:
class Object {
public:
static Costs m_costs; // All objects (A,B,...) would cost the same
}
将成本直接关联到对象的正确方法是什么?
【问题讨论】:
-
您的 getCosts() 函数是否访问 Object 或其子项中的任何其他成员?还是只是 Costs 成员的吸气剂?
-
它只是一个getter,基本上是一个带有一些整数的类,请查看我刚刚添加的编辑
标签: c++ inheritance static polymorphism