澄清`this`关键字

时间:2012-12-07 16:48:11

标签: c++ pointers this

很抱歉,如果这是一个微不足道的问题:

实施1:

class Foo
{
    protected: int bar;

    public: Foo(int bar)
      {
        this->bar =bar;
      }
};

实施2:

class Foo
{
    protected: int bar;

    public: Foo(int bar)
      {
        this.bar =bar;
      }
};

实施2的输出:

request for member ‘x’ in ‘this’, which is of pointer type ‘Foo* const’ (maybe you meant to use ‘->’ ?)

所以this是一个指针,而this问题在代码中有语法错误

1 个答案:

答案 0 :(得分:6)

您指的问题包含用C#编写的代码示例,而不是C ++。是的,在C ++中,this是一个指针,必须取消引用才能访问它指向的对象的任何成员。