基类属性的初始化不同

时间:2015-08-13 08:45:49

标签: c++ inheritance constructor

考虑具有属性

的基类
class Base 
{
  protected:

  AttributeBase * elementPtr;
  ...
};

派生类

class Derived : public Base
{
  ...
};

我还有一个AttributeDerived来自AttributeBase

的课程Base

当我创建类elementPtr的对象时,我希望以这种方式初始化elementPtr = new AttributeBase()

Derived

但是当我创建类elementPtr的对象时,我希望以这种方式初始化elementPtr = new AttributeDerived()

- (void)btnChangeImage {
    UIButton *btn;

    if (btn.selected) {
        [btn setImage:[UIImage imageNamed:@"selected.png"] forState:UIControlStateSelected];
    } else {
        [btn setImage:[UIImage imageNamed:@"diselected.png"] forState:UIControlStateNormal];
    }
}

最干净的方法是什么?

2 个答案:

答案 0 :(得分:5)

您可以向protected添加Base构造函数,该构造函数允许派生类传递elementPtr以使用:

Base (AttributeBase* elementPtr) : elementPtr(elementPtr)
{}

然后在派生类中,调用该构造函数:

Derived() : Base(new AttributeDerived())
{}

如果您使用C ++ 11,那么您可以让其他Base构造函数委托受保护的构造函数来限制代码重复。

答案 1 :(得分:4)

您可以为不同目的添加Base的不同ctors:

class Base 
{
  protected:

    AttributeBase * elementPtr;
    Base(AttributeBase * p) : elementPtr(p) {}

  public:
    Base() : elementPtr(new AttributeBase) {}
};

class Derived : public Base
{
  public:
    Derived() : Base(new AttributeDerived) {}
};

然后

Base b;    // elementPtr = new AttributeBase()
Derived d; // elementPtr = new AttributeDerived()