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


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

承认以下代码:

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

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


4513
2018-04-27 22:03


起源

当然,如果 bar 是虚函数而不是数据成员,两者之间存在差异。另请注意,您可以将它们组合起来 this->Foo::bar。 - dyp


答案:


课内 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
  }
};

12
2018-04-27 22:13



谢谢 !我知道了 ;) - Bryan Peeters


他们做同样的事情成员。

但是,你无法使用 this-> 区分类层次结构中的同名成员。你需要使用 ClassName:: 版本来做到这一点。


4
2018-04-27 22:14



gcc不同意这一点 this-> 不适用于静态变量: ideone.com/N4dSDD - Xymostech
@Xymostech我很困惑。 clang 也接受它。谢谢你指出来。 - pmr
没问题。我也有点困惑。 - Xymostech


对于我学习摆弄C / C ++的东西,使用 - > on something主要用于指针对象,而using ::用于作为命名空间或超类的一部分的类,它是一般的类。你包括在内


0
2018-04-27 22:06



我仍然没有看到差异.. - Bryan Peeters
好吧,对于::它就像使用std :: cout <<“”;使用::意味着您正在使用std命名空间的直接实现,而不是使用命名空间std;在你的文件中。 - >就像你“指向”指向另一个对象的指针。这就是我看到他们使用的方式。 - user2277872


它还允许您引用具有相同名称的另一个类(大多数情况下是基类)的变量。对我来说,这个例子很明显,希望它对你有所帮助。

#include <iostream>
using std::cout;
using std::endl;

class Base {
public:
    int bar;
    Base() : bar(1){}
};

class Derived : public Base {
public:
    int bar;

    Derived() : Base(), bar(2) {}

    void Test() {
        cout << "#1: " << bar << endl; // 2
        cout << "#2: " << this->bar << endl; // 2
        cout << "#3: " << Base::bar << endl; // 1
        cout << "#4: " << this->Base::bar << endl; // 1
        cout << "#5: " << this->Derived::bar << endl; // 2
    }
};

int main()
{
    Derived test;
    test.Test();
}

这是因为存储在类中的真实数据是这样的:

struct {
    Base::bar = 1;
    Derived::bar = 2; // The same as using bar
}

0
2018-04-27 22:17