2017-06-14 80 views
1

我有不同的可生成對象。每種對象類型都有不同的成本。我想檢查用戶是否可以在創建它之前負擔特定對象之前。下面的方法不尊重這個要求:在子類中具有不同值的靜態基類屬性

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有道Ÿ將成本與物品相關聯?

+0

您的getCosts()函數是否可以訪問Object或其子項中的其他成員?或者它只是Costs會員的吸氣劑? – SideLobe

+0

這只是一個吸氣者,基本上是一些有整數的類,請參閱我剛添加的編輯 – Anonymous

回答

2

你可以通過模板提供以下信息:

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; 
1

靜態函數不能是虛擬的,但仍可以被重寫。簡單地說,使用的版本不取決於對象的實際類,而僅取決於用於訪問它的指針的聲明類。

但是,這可以用來做一個測試創建一個對象之前:

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以引發編譯時錯誤。

相關問題