2013-04-27 55 views
11

我想知道C++中的一些东西。this-> field和Class :: field之间的区别?

承认以下代码:

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

里面我的课,是有this->barFoo::bar之间有什么区别?有一种情况是无效的吗?

+2

当然,如果'bar'是一个虚函数,而不是一个数据成员,还有两者之间的差异。另外请注意,您可以像'this-> Foo :: bar'一样将它们组合起来。 – dyp 2013-04-27 22:21:44

回答

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

谢谢!我得到了它;) – 2013-04-27 22:14:59

0

对于我已经学会了用C/C++摆弄周围,使用 - >上的东西主要是为指针对象,并使用::用于那些命名空间或超类是部分类包括你的任何一般类别

+0

我还没有看到其中的差别.. – 2013-04-27 22:11:57

+0

那么,对于::它像使用std ::法院<<“”;使用::意味着你正在使用std命名空间的直接实现,而不是使用namespace std;在你的文件中。 - >就像是“指向”另一个对象的指针。这就是我看到他们使用的方式。 – user2277872 2013-04-27 22:22:35

4

他们做同样的事情成员。

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

+3

GCC不同意'这个 - >'不与静态变量工作:http://ideone.com/N4dSDD – Xymostech 2013-04-27 22:16:54

+0

@Xymostech我感到困惑。 '铛'也可以接受。感谢您指出。 – pmr 2013-04-27 22:18:37

+1

没问题。我也有点困惑。 – Xymostech 2013-04-27 22:19:35

0

它还允许你你用相同的名字引用(在大多数情况下,基类)其他类的变量。对我而言,从这个例子中可以看出,希望它能帮助你。

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