通过引用传递父对象 [英] Passing parent object by reference

查看:69
本文介绍了通过引用传递父对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在库中有以下代码:

class Parent
{
    //some data and functions
};

void myfunc(Parent& ref);

并且我想在我的应用程序中执行以下代码:

and I want to do this code in my application:

class Child : public Parent
{
   // some other data and functions
   void dostuff()
   {
       myfunc(*this);
   }
};

通过*这样安全吗? (不切片,不复制,...) 这样调用myfunc更好吗:

Is it safe to pass *this? (no slicing, no copying, ...) Is it better to call myfunc like this:

myfunc( * ((Parent*)this) )

请注意,我无法控制myfunc内部发生的事情,在某些情况下,我什至不知道其中内部发生的事情.

Note that I don't have control on what happens inside myfunc, in some cases I don't even know what happens inside there.

我曾经多次使用指针传递父对象,并且已经习惯了,但是以前从未使用过引用传递父对象.

I used passing-parent-by-pointer many times and I am used to it, but have never used passing-parent-by-reference before.

推荐答案

myfunc(*this)很好,只要声明myfunc引用即可.

myfunc(*this) is fine, so long as myfunc is declared to take a reference -- which it is.

这不会复制对象.它将传递对原始对象的引用.此外,它不会对对象进行切片.引用的类型将为Base&,但引用的对象将保持不变.

This will not copy the object. It will pass a reference to the original object. Furthermore, it will not slice the object. The reference will be of type Base&, but the object to which it refers will be unchanged.

就这么知道,如果您随后要在此Base&上调用多态方法(例如,virtual),则多态性仍然可以正常工作,并且可以执行您期望的操作-就像您要调用的方法一样通过指针.换句话说:

Just so you know, if you were then to call polymorphic (eg, virtual) methods on this Base&, polymorphism will still work right and do what you'd expect -- just like if you were to call through a pointer. In other words:

Base& b = *derived;
b.SomeVirtualFoo();

...将具有与以下相同的作用:

...will have the same effect as:

Base* b = derived;
b->SomeVirtualFoo();

这篇关于通过引用传递父对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆