2012-10-14 139 views

回答

5

在这种情况下,没有区别。

这个符号:

obj.Class::member

只是为了解决来自继承来的含糊之处:

class A { 
public: 
    int a; 
} 

class B { 
public: 
    int a; 
} 

class C : public A, B { 
    void func() { 
     // this objects holds 2 instance variables of name "a" inherited from A and B 
     this->A::a = 1; 
     this->B::a = 2; 
    } 

} 
6

的目的没有区别。在这种情况下,ar的显式名称空间限定是多余的。

在(多重,非虚拟)继承重新定义名称ar的情况下,它可能不是多余的。样品(人为):

#include <string> 

class A 
{ 
    public: 
     int *ar; 
     A() { ar = new int[100]; } 
     // unrelated, but prevent leaks: (Rule Of Three) 
     ~A() { delete[] ar; } 
    private: 
     A(A const&); 
     A& operator=(A const&); 
}; 

class B : public A 
{ 
    public: 
     std::string ar[12]; 
}; 


int main() 
{ 
    B ob; 
    ob.A::ar[0] = 200; 
    ob.ar[0] = "hello world"; 
} 

看到它在http://liveworkspace.org/code/d25889333ec378e1382cb5af5ad7c203

+0

你能解释一下你在A班写的私人代码吗? – Rushil

+1

@Rushil嗯,这是非常关键的问题:这是防止“A”被复制的最快方法(这会导致'A :: ar'的双重删除)。它被称为[Rule Of Three](http://stackoverflow.com/questions/4172722/what-is-the-rule-of-ree),或者在C++ 11 [Rule Of Zero](http:// rmartinho) .github.com/2012/08/15/rule-of-zero.html)代替:) – sehe

+0

好的。我知道这是脱离主题,但我想知道这意味着什么。 :-) – Rushil

1

在这种情况下是没有区别的。然而,想象ob是从类A和类B继承的类C,并且A和B都有一个字段ar。那么就没有其他的方法可以访问ar,而是明确地指定你正在引用哪个继承的数据成员。

0

你应该阅读本

ob.A::ar[0] = 200; 
ob.ar[0] = 200; 

这样

A::ar[0]它是ar[0]同样的事情,所以2行基本上是相同的事情,运营商::用于指示所谓分辨率的命名空间,或者仅仅是命名空间。

因为ob是类型A的对象,所以命名空间分辨率是隐含的,在访问ar[0]之前,您不需要A::