gpt4 book ai didi

c++ - 在运行时创建相关类型的最佳方法是什么?

转载 作者:行者123 更新时间:2023-11-28 08:14:10 25 4
gpt4 key购买 nike

如何在运行时确定与另一个类相关的类的类型?

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

有没有不需要定义或复制粘贴的更简单的方法?

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

#include <iostream>
#include <string>

class model;

class view {
public:
view( model *m ) {}
virtual std::string display() {
return "view";
}
};

#define RELATED_CLASS(RELATED)\
typedef RELATED relatedType;\
virtual relatedType*createRelated(){\
return new relatedType(this);}

class model {
public:
RELATED_CLASS(view)
model() {}
};

class otherView : public view {
public:
otherView( model *m ) : view(m) {}
std::string display() {
return "otherView";
}
};

class otherModel : public model {
public:
RELATED_CLASS(otherView)
otherModel() {}
};

class control {
public:
control( model *m ) : m_(m),
v_( m->createRelated() ) {}
~control() { delete v_; }
std::string display() {
return v_->display();
}
model *m_;
view *v_;
};

int main( void ) {
model m;
otherModel om;

model *pm = &om;

control c1( &m );
control c2( &om );
control c3( pm );

std::cout << c1.display() << std::endl;
std::cout << c2.display() << std::endl;
std::cout << c3.display() << std::endl;
}

最佳答案

您可以改用模板来避免#defines,但是,无论哪种方式,请注意您实际上是在使用 otherModel 的 createRelated 方法重载返回类型。

可能有更好的方法来完成您想要做的事情。

#include <iostream>
#include <string>

class model;

class view {
public:
view( model *m ) {}
virtual std::string display() {
return "view";
}
};

class model {
public:
virtual view* createRelated() { return new view (this); }
model() {}
};


template <class Related>
class relatedModel : public model
{
public:
relatedModel() : model() {}
virtual view* createRelated() { return new Related(this);}
} ;


class otherView : public view {
public:
otherView( model *m ) : view(m) {}
std::string display() {
return "otherView";
}
};

class control {
public:
control( model *m ) : m_(m),
v_( m->createRelated() ) {}
~control() { delete v_; }
std::string display() {
return v_->display();
}
model *m_;
view *v_;
};

int main( void ) {
relatedModel<view> m;
relatedModel<otherView> om;

model *pm = &om;

control c1( &m );
control c2( &om );
control c3( pm );

std::cout << c1.display() << std::endl;
std::cout << c2.display() << std::endl;
std::cout << c3.display() << std::endl;
}

关于c++ - 在运行时创建相关类型的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8185115/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com