简体   繁体   English

这两个陈述之间有什么区别

[英]What's the difference between these two statements

What's the difference between these two statements? 这两个陈述有什么区别?

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

where ob is an object of class A 其中obA类的对象

class A
{
    public:
        int *ar;
        A()
        {
            ar = new int[100];
        }
};

There is no difference. 没有区别。 The explicit namespace qualification of ar is redundant in this case. 在这种情况下, ar的显式命名空间限定是多余的。

It might not be redundant in cases where (multiple, nonvirtual) inheritance redefines the name ar . 在(多个非虚拟)继承重新定义名称ar情况下,它可能不是多余的。 Sample (contrived): 样本(人为):

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

See it on http://liveworkspace.org/code/d25889333ec378e1382cb5af5ad7c203 请参阅http://liveworkspace.org/code/d25889333ec378e1382cb5af5ad7c203

In this case there is no difference. 在这种情况下,没有区别。

This notation: 这种表示法:

obj.Class::member

is only to solve the ambiguities coming from inheritance: 只是为了解决继承的模糊性:

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

}

In this case there is no difference. 在这种情况下,没有区别。 However imagine that ob is of class C that inherits both from class A and class B and both A and B have a field ar. 但是,假设ob是C类,它继承了A类和B类,A和B都有一个字段ar。 Then there will be no other way to access ar but to explicitly specify which of the inherited data members you are refering to. 然后,没有其他方法可以访问ar,但是要明确指定要引用的继承数据成员。

You are supposed to read this 你应该读这个

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

like this 像这样

A::ar[0] it's the same thing for ar[0] , so the 2 rows are basically the same thing and the operator :: is used to indicate the so called resolution of the namespace , or just the namespace. A::ar[0]这是同样的事情ar[0]所以两行基本上是相同的事情,操作员::用于指示命名空间的所谓的分辨率 ,或者仅仅是命名空间。

since ob is an object of type A, the namespace resolution is implicit and you do not need A:: before accessing ar[0] . 因为ob是A类型的对象,所以命名空间解析是隐式的,在访问ar[0]之前不需要A::

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM