考虑具有属性
的基类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];
}
}
最干净的方法是什么?
答案 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()