如何从被传递的对象中通过引用传递 self

How to pass self by reference from within the object being passed?

本文关键字:self 引用 对象      更新时间:2023-10-16

我对需要使用的语法感到困惑。

我有:

class Foo {
public:
    void bar(Baz& grr){
    }
}

另一类:

class Baz{
}

和:

class Jay : public Baz{
public:
   void doStuff(){
        Foo thing();
        thing.bar(); //Here is the problem ? How do I pass this instance to this function ?
   }
}

如何从doStuff()内将Jay实例传递给Foo::bar(Baz& grr)?如果我尝试使用this编译器说使用 * 取消引用它。我该怎么做?

尝试完全按照编译器的建议进行操作:

thing.bar(*this);

通过取消引用指针,可以"创建"引用。

this是指向当前对象的指针。你需要"取消引用"它才能获得对象的引用:

thing.bar(*this);

您可以使用 * 运算符取消引用,如 *this .取消引用返回指向的对象,由于this是指向当前实例的指针,*this将返回当前实例的对象。

但是请注意,如果保存此引用并且该实例超出范围,它将被销毁,并且您将留下一个悬而未决的引用,该引用在尝试读取时会导致未定义的行为。