c++ - 如何动态创建相关类型?

标签 c++ inheritance dynamic

如何动态确定与另一个类相关的类的类型?

我找到了一个解决方案,唯一的问题是我最终不得不使用一个必须在所有派生类中使用的定义。

有没有更简单的方法来做到这一点,不需要为添加的所有类进行维护?

注意事项:类和相关类总是有各自的基类,不同的类可以共享一个相关类,在示例中我希望控制类拥有 View 。

这就是我现在拥有的。我唯一需要维护的是开关,但我想要它,所以我只需要添加代码而不是返回并更改它。

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

最佳答案

一个可能的解决方案是更改模型以接受指向创建相关类的函数的指针,而不是传递“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);

希望对您有所帮助。

关于c++ - 如何动态创建相关类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8232599/

相关文章:

java - 深度嵌套继承——好的还是坏的做法?

R Shiny : Isolate dynamic output within dynamic tabs

c - 尽可能少链接的 dlopen/dlsym

c++ - 如何读取 C++ 中的嵌入式代码签名?

c++ - 对未初始化内存使用算法的优点

java - 根据类实例进行操作

java 实例方法和变量的继承解析

dynamic - 如何在*Application_Start之后动态添加OData Web Api路由?

c++ - 将字节写入文件

c++ - 调用 new 时出现内存故障