创建从不同对象提供的类型继承的类的对象
我有以下类,
class CommonStyle
{};
class Style1 : public CommonStyle
{};
class Style2 : public CommonStyle
{};
class Style3 : public CommonStyle
{};
template<typename T> class ZStyle : public T
{
};
我有可以是 Style1、Style2、Style3 类型的对象。 如何根据提供的对象创建从 Style1 或 Style2 或 Style3 继承的 ZStyle 对象?
//pseudo-code
int _tmain(int argc, _TCHAR* argv[])
{
CommonStyle* obj1 = new Style1();
CommonStyle* obj2 = new Style2();
CommonStyle* obj3 = new Style3();
ZStyle* zobj1 = create_object_inherited_from_style1(obj1);
ZStyle* zobj2 = create_object_inherited_from_style2(obj2);
ZStyle* zobj3 = create_object_inherited_from_style3(obj3);
}
是否可以避免dynamic_cast?
I have the following classes
class CommonStyle
{};
class Style1 : public CommonStyle
{};
class Style2 : public CommonStyle
{};
class Style3 : public CommonStyle
{};
template<typename T> class ZStyle : public T
{
};
I have object which can be type of Style1, Style2, Style3.
How can I create object of ZStyle inherited from Style1 or Style2 or Style3 depend on provided object?
//pseudo-code
int _tmain(int argc, _TCHAR* argv[])
{
CommonStyle* obj1 = new Style1();
CommonStyle* obj2 = new Style2();
CommonStyle* obj3 = new Style3();
ZStyle* zobj1 = create_object_inherited_from_style1(obj1);
ZStyle* zobj2 = create_object_inherited_from_style2(obj2);
ZStyle* zobj3 = create_object_inherited_from_style3(obj3);
}
Is it possible to avoid dynamic_cast?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我可能会回答不同的问题,但这可能是您问题的解决方案。
虚拟构造函数习惯用法可能会有所帮助。
您在基类中创建一个名为 clone() 的虚拟方法,该方法在后代类中被重写。然后,你写
CommonStyle* zobj1 = obj1.clone();
CommonStyle* zobj2 = obj2.clone();
CommonStyle* zobj3 = obj3.clone();
这会产生三个具有静态类型 CommonStyle 的对象,但动态类型取决于它们是从哪个对象克隆的。
I might be answering a different question, but it may be the solution to you problem.
The virtual constructor idiom may be helpful.
You create a virtual method called clone() in the base class, which is overridden in descendant classes. Then, you write
CommonStyle* zobj1 = obj1.clone();
CommonStyle* zobj2 = obj2.clone();
CommonStyle* zobj3 = obj3.clone();
This results in three objects with static type CommonStyle, but dynamic type depending on what object they were clone()'d from.
下面类似 CRTP 的修改如何:
用法:
或者,您可以将
z()
的返回类型设为CommonBase *
,这样您就无需担心最后一行的类型依赖性。How about the following CRTP-like modification:
Usage:
Alternatively, you can make the return type of
z()
to beCommonBase *
so you don't need to worry about the type dependence in the last line.