将继承的类传递给 c++ 中的函数
我在 C++ 中的继承方面遇到了一个小问题,我不太明白。
所以,假设我有一些从 stl 列表派生的类,即:
class Class1: public list<T>{
virtual func1();
}
class Class2 : public Class1<w/e>{
func1();
}
我遇到的问题是将这些类传递给函数时。如何正确地将其中一个实例传递给函数,以便在可以传递任一类型的实例的情况下它将使用正确的虚函数?我已经有一段时间没有做过继承和虚函数了,所以我在这里有点生疏。 (假设该函数不是类的成员函数)。
I'm having a little problem with inheritance in C++ that I can't quite figure out.
So, say I have some classes derived from stl list, i.e:
class Class1: public list<T>{
virtual func1();
}
class Class2 : public Class1<w/e>{
func1();
}
The problem I'm having is when passing these to a function. How can I properly pass an instance of one of these to a function so that it will use the proper virtual function if it is possible for an instance of either type to be passed? I haven't done inheritance and virtual functions in awhile so I am a bit rusty here.
(This assuming that the function is not a member function of the classes).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要将它们作为引用
或指针传递给函数;
它应该只是简单地调用虚拟方法的正确版本。
如果您在没有其中任何一个的情况下传递它们,则
该对象将被复制构造为始终是函数中的 Class1,并且将始终调用 Class1::func1()
You will need to pass them to the function as a reference
or as a pointer;
and it should just plain call the correct version of the virtual method.
If you pass them without either of those
The object will be copy constructed to always be a Class1 in the function, and will always call Class1::func1()