【问题标题】:What am I supposed to do with &this?我应该用 &this 做什么?
【发布时间】:2012-11-24 06:22:02
【问题描述】:

我有一些代码需要使用双指针。具体来说,我很好奇为什么我不能在...的上下文中说&this

class Obj {
public:
    void bar();
};

void foo(Obj **foopa)
{
    // do etc with your foopa.  maybe lose the foopa altogether. its nasty imo.
}

void Obj::bar()
{
    // call foo(Obj **)
    foo(&this);  // Compiler Err:  Address extension must be an lvalue or a function designator.
}

左值?功能指示符?喜欢听到回音。

【问题讨论】:

  • 请用编程语言标记您的问题。
  • 这一切都取决于为什么你需要一个指向指针的指针。

标签: c++ reference this keyword semantics


【解决方案1】:

因为“this”是一个特殊的指针,你不应该改变它,但你可以做一些类似的事情,不要把“Obj *t”放在函数中,因为它在函数结束时被销毁,所以它必须是静态的。

class Obj;
Obj *t;

class Obj {
public:
    void bar();
};

void foo(Obj **foopa)
{
    // do etc with your foopa.  maybe lose the foopa altogether. its nasty imo.
}

void Obj::bar()
{
    // call foo(Obj **)
    t = this;
    foo(&t);  // Compiler Err:  Address extension must be an lvalue or a function designator.
}

【讨论】:

  • “不应该”是轻描淡写的。它和3 一样不变。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-02-12
  • 2013-03-29
  • 2011-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多