【问题标题】:Static base class attribute with different values in subclasses子类中具有不同值的静态基类属性
【发布时间】: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


【解决方案1】:

您可以通过模板提供此信息:

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

这样您可以在决定是否实例化 Object_A 之前检索特定的 Costs 实例:

Costs costsA = Object_A::m_costs;

【讨论】:

    【解决方案2】:

    静态函数不能是虚拟的,但仍然可以被覆盖。只是使用的版本不依赖于对象的实际类,而只依赖于用于访问它的指针的声明类。

    但这可以用来在创建对象之前进行测试:

    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-&gt;getCost() 将独立于实际类返回Object 版本- 如果您尝试使用它,您甚至永远不能在Object 类中声明getCost 以引发编译时错误。

    【讨论】:

      猜你喜欢
      • 2013-02-01
      • 2015-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-30
      • 2018-12-31
      相关资源
      最近更新 更多