【问题标题】:Difference between this->field and Class::field?this->field 和 Class::field 之间的区别?
【发布时间】:2013-04-21 20:38:34
【问题描述】:

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

承认以下代码:

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

在我的班级里,this->barFoo::bar 有什么区别吗?有没有无效的情况?

【问题讨论】:

  • 当然,如果bar是一个虚函数而不是一个数据成员,那么两者是有区别的。另请注意,您可以像 this->Foo::bar 一样组合它们。

标签: c++ class pointers this scope-resolution


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    他们做同样的事情。

    但是,您将无法使用this-> 来区分类层次结构中的同名成员。您需要使用ClassName:: 版本来执行此操作。

    【讨论】:

    • gcc 不同意 this-> 不适用于静态变量:ideone.com/N4dSDD
    • @Xymotech 我很困惑。 clang 也接受它。感谢您指出。
    • 没问题。我也有点困惑。
    【解决方案3】:

    对于我所学的 C/C++ 摆弄,在某物上使用 -> 主要用于指针对象,而使用 :: 用于作为命名空间的一部分的类或通用的超类你所包含的任何类别

    【讨论】:

    • 嗯,对于 :: 就像使用 std::cout 就像您“指向”指向另一个对象的指针。这就是我看到他们使用的方式。
    【解决方案4】:

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

    #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
    }
    

    【讨论】:

      猜你喜欢
      • 2015-12-26
      • 2011-11-22
      • 1970-01-01
      • 2011-02-14
      • 2021-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-05
      相关资源
      最近更新 更多