如何确定与其他类动态相关的类的类型?如何动态创建相关类型?
我已经想出了一个解决方案,唯一的问题是我最终不得不使用必须在所有派生类中使用的定义。
有没有更简单的方法来做到这一点,不需要保养永远增加的类?
注意事项:类和相关类将始终具有其各自的基类,不同的类可以共享相关的类,并且如示例中我希望控件类拥有该视图。
这就是我现在拥有的。我唯一需要维护的就是交换机,但是我想拥有它,所以我只需要添加代码就可以返回并更改它。
#include <iostream>
#include <string>
class model
{
public:
model(int id) : id(id) {}
int id;
};
class view
{
public:
view(model *m) {}
virtual std::string display()
{
return "view";
}
};
class otherView : public view
{
public:
otherView(model *m) : view(m) {}
std::string display()
{
return "otherView";
}
};
class control
{
public:
control(model *m) : m_(m), v_(createRelated()) {}
~control()
{
delete v_;
}
std::string display()
{
if (v_)
return v_->display();
return "No view";
}
view *createRelated()
{
switch(m_->id)
{
case 0:
return new view(m_);
case 1:
return new otherView(m_);
default:
return NULL;
}
}
model *m_;
view *v_;
};
int main(void) {
model m(0);
model om(1);
model nm(2);
control c1(&m);
control c2(&om);
control c3(&nm);
std::cout << c1.display() << std::endl;
std::cout << c2.display() << std::endl;
std::cout << c3.display() << std::endl;
}