将继承的类传递给 c++ 中的函数

发布于 2024-12-28 14:32:32 字数 340 浏览 2 评论 0原文

我在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

姜生凉生 2025-01-04 14:32:32

您需要将它们作为引用

int function(Class1& obj);

或指针传递给函数;

int function(Class1* obj);

它应该只是简单地调用虚拟方法的正确版本。

如果您在没有其中任何一个的情况下传递它们,则

int function(Class1 obj);

该对象将被复制构造为始终是函数中的 Class1,并且将始终调用 Class1::func1()

You will need to pass them to the function as a reference

int function(Class1& obj);

or as a pointer;

int function(Class1* obj);

and it should just plain call the correct version of the virtual method.

If you pass them without either of those

int function(Class1 obj);

The object will be copy constructed to always be a Class1 in the function, and will always call Class1::func1()

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文