2011-11-22 134 views
0

如何確定與其他類動態相關的類的類型?如何動態創建相關類型?

我已經想出了一個解決方案,唯一的問題是我最終不得不使用必須在所有派生類中使用的定義。

有沒有更簡單的方法來做到這一點,不需要保養永遠增加的類?

注意事項:類和相關類將始終具有其各自的基類,不同的類可以共享相關的類,並且如示例中我希望控件類擁有該視圖。

這就是我現在擁有的。我唯一需要維護的就是交換機,但是我想擁有它,所以我只需要添加代碼就可以返回並更改它。

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

回答

1

一種可能的解決方案是改變模型接受一個指針,它指向創建相關類的函數,而不是傳遞一個的「id」:

typedef view* (*make_function)(model*); 

class model 
{ 
public: 
    model(make_function a_make) : make_(a_make) {} 
    view* make() const { return make_(this); } 
... 
private: 
    make_function make_; 
}; 

每個view的類來提供一個靜態方法,該方法創建自身的實例:

class view 
{ 
public: 
    static view* make(model* m) { return new view(m); } 
}; 

class otherView: public view 
{ 
public: 
    static view* make(model* m) { return new otherView(m); } 
}; 

然後 'createRelated()' 將成爲:

view* control::createRelated() 
{ 
    return m_->make(); 
} 

示例使用:

model m1(&view::make); 
model m2(&otherView::make); 

希望有幫助。

0

您可能需要一些虛擬功能。即使通過從類型A衍生B型的一個目的:

void f(A &objA) { 
    objA.f(); 
} 

int main() { 
    B objB; 
    f(objB); 
    return 0; 
} 

如果A :: f()是定義爲虛擬的,則B :: F()將被調用。所以你不需要知道objA是一個objB。