我有以下结构
class Base
{
public:
Base(Type);
virtual render
}
class A
{
public:
Base(Type == A);
void render()
}
class B
{
public:
Base(Type == B);
void render()
}
void client_function()
{
Base baseObject(A);
//Base is an instance of class A
baseObject.render()//runs class A render
}
据我所知,上述代码中的某些内容不是 C++,它们与 Haskell 中发现的模式匹配密切相关,但这是我能找到的最好的方式来说明我的问题,而无需已经知道答案了;)
在写作中,我希望客户端能够创建一个基础对象并将对象的类型作为参数传递,返回对象的正确规范,并且客户端不需要关心它,只需知道运行渲染将运行正确的特定渲染。
如果我不清楚,请随时提问:)
I have the following structure
class Base
{
public:
Base(Type);
virtual render
}
class A
{
public:
Base(Type == A);
void render()
}
class B
{
public:
Base(Type == B);
void render()
}
void client_function()
{
Base baseObject(A);
//Base is an instance of class A
baseObject.render()//runs class A render
}
There are things in the above code that are not c++ as far as I am aware, they are closely related to pattern matching found in Haskell for example, but this is the best way I could find to illustrate my question without already knowing the answer ;)
In writing I want the client to be able to create a base object and pass the type of object as an argument, the correct specification of the object is returned and the client need not care less about it, just knows that running render will run the correct specific render.
Please feel free to ask questions if I have been unclear :)
发布评论
评论(4)
我认为您需要阅读有关虚拟函数和继承的内容:
http://www .parashift.com/c++-faq-lite/virtual-functions.html
http://www.parashift.com/c++-faq-lite/proper-inheritance.html
http://www.parashift.com/c++-faq-lite/abcs.html
I think you need to read about virtual functions and inheritance:
http://www.parashift.com/c++-faq-lite/virtual-functions.html
http://www.parashift.com/c++-faq-lite/proper-inheritance.html
http://www.parashift.com/c++-faq-lite/abcs.html
您需要运行时多态性。构造函数没有太多重要的部分。您必须将
Base
继承到A
和B
中。例如:现在您可以根据您的要求使用。
You need run-time polymorphism. There is not much important part of constructor. You have to inherit the
Base
intoA
andB
. For example:Now you can use as per your requirement.
我不确定我是否理解你的问题。在 C++ 中,您无法在运行时选择基类,但您当然可以让基类依赖于派生类。这是通过使用模板和所谓的奇怪的重复模板模式来完成的:
希望这能回答您的问题问题。
I'm not sure I understood your question. In C++ you cannot choose your base class at runtime, but you certainly can have your base class depend from the derived class. This is done by using templates and what is known as the Curiously Recurring Template Pattern:
Hope this answers your question.
您所要求的正是继承的用途:从专用于功能的类层次结构创建对象。
在您的示例中,除了语法问题之外,一切都会按您的预期工作,即方法
A::render
将被调用,即使您在编译时不知道该对象(声明为 < code>Base,确实是一个A
。这就是虚拟继承的魔力。What you ask for is exactly what inheritance is for: creating object from a class hierarchy that specializes a functionality.
In your example, apart from syntax problems, things will work as you expect, i.e. method
A::render
will be called, even if you don't know at compile time that object, declared as aBase
, is indeed aA
. That's virtual inheritance magicness.