this-> field和Class :: field之间的区别?

Bry*_*ers 11 c++ pointers class this scope-resolution

我想知道C++中的一些东西.

承认以下代码:

int bar;
class Foo
{
public:
    Foo();
private:
    int bar;
};
Run Code Online (Sandbox Code Playgroud)

在我班上,this->bar和之间有什么区别Foo::bar?是否存在一个无效的情况?

Jon*_*Jon 12

内部类Foo(特别是)有两个假设没有区别bar不是static.

Foo::bar被称为成员的完全限定名称bar,并且此形式在层次结构中可能有多个类型定义具有相同名称的成员的情况下非常有用.例如,你需要Foo::bar这里写:

class Foo
{
  public: Foo();
  protected: int bar;
};

class Baz : public Foo
{
  public: Baz();
  protected: int bar;

  void Test()
  {
      this->bar = 0; // Baz::bar
      Foo::bar = 0; // the only way to refer to Foo::bar
  }
};
Run Code Online (Sandbox Code Playgroud)