我有不同的可生成對象。每種對象類型都有不同的成本。我想檢查用戶是否可以在創建它之前負擔特定對象之前。下面的方法不尊重這個要求:在子類中具有不同值的靜態基類屬性
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有道Ÿ將成本與物品相關聯?
您的getCosts()函數是否可以訪問Object或其子項中的其他成員?或者它只是Costs會員的吸氣劑? – SideLobe
這只是一個吸氣者,基本上是一些有整數的類,請參閱我剛添加的編輯 – Anonymous