如何確定與其他類動態相關的類的類型?如何動態創建相關類型?
我已經想出了一個解決方案,唯一的問題是我最終不得不使用必須在所有派生類中使用的定義。
有沒有更簡單的方法來做到這一點,不需要保養永遠增加的類?
注意事項:類和相關類將始終具有其各自的基類,不同的類可以共享相關的類,並且如示例中我希望控件類擁有該視圖。
這就是我現在擁有的。我唯一需要維護的就是交換機,但是我想擁有它,所以我只需要添加代碼就可以返回並更改它。
#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;
}