[英]Passing reference of the current object in a class member function in C++
Just like the this
pointer is used to pass the pointer to the current object, how do I pass reference to the current object ? 就像使用
this
指针将指针传递给当前对象一样,如何将引用传递给当前对象?
class UseMe
{
public:
UseMe_funcReference(base&);
UseMe_FuncPointer(base *)
}
class base{
..........
}
class Abc:public base
{
public:
friend UseMe;
UseMe innerObj;
Func1()
{
(this->innerObj).UseMe_funcPointer(this); // This passes pointer to current object
(this->innerObj).UseMe_funcReference(HOW_TO_PASS_REFERENCE_TO_CURRENT_OBJECT);
}
}
You don't notate pass-by-reference that at the call site , there you use exactly the same syntax as a regular pass-by-value. 您无需在调用站点上注明传递引用,您在此处使用的语法与常规传递值完全相同。
In the actual function, you use &
to denote that the parameter is passed by reference. 在实际函数中,使用
&
表示该参数是通过引用传递的。 For example consider the function foo
that takes a bar
as a reference: 例如,考虑函数
foo
采用一个bar
作为参考:
void foo(bar& reference);
Then you could use foo(*this)
at the call site, if this
is a bar*
(or related) type. 然后,如果
this
是bar*
(或相关)类型,则可以在呼叫站点上使用foo(*this)
。
您只需要使用*this
,就像从赋值运算符返回对self的引用时一样。
this
is a pointer to the current object. this
是指向当前对象的指针。
*this
is a name for the current object. *this
是当前对象的名称。
Contrary to what some of the other people have said here, it is not a reference (dereferencing a T*
gives you an lvalue T
), but you can bind a reference to it just as you would elsewhere. 与其他人在这里所说的相反,它不是一个引用(对
T*
引用会给您一个左值T
),但是您可以像在其他地方一样对它进行绑定。
tl;dr: dereference it, as you would any other pointer tl; dr:取消引用它,就像其他任何指针一样
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.