用’.’替换’: :’会在 C + + 中产生歧义吗?

在 C + + 中,操作符 ::用于访问命名空间或类中的类、函数和变量。

如果语言规范在这些情况下使用 .而不是 ::,就像访问一个对象的实例变量/方法一样,那么是否会导致 ::没有出现的可能的歧义?

考虑到 C + + 不允许变量名也是类型名,我想不出有什么情况会发生这种情况。

澄清: 我不是问为什么选择 ::而不是 .,只是如果它也可以工作?

6273 次浏览

Due to attempts to make C++ mostly compatible with the existing C code (which allows name collisions between object names and struct tags), C++ allows name collisions between class names and object names.

Which means that:

struct data {
static int member;
};


struct data2 {
int member;
};


void f(data2& data) {
data.member = data::member;
}

is legit code.

An example where both are valid, but refer to different objects:

#include <iostream>


struct A {
int i;
};


struct B {
int i;
A B;
};


int main() {
B x {0, 1};
std::cout << x.B.i << '\n';
std::cout << x.B::i << '\n';
}

See live on coliru.

There is difference between a::b and a.b where :: implies that a used as namespace, which means that it is namespace or typename. Provided that C++ supports non-virtual plural inheritance and that a variable can have same name as a type, this strips chances of referencing wrong object. It's necessary for template metaprogramming.

Another example would be &B::foo vs &B.foo in context of class B.

Let extend @Deduplicator example:

#include <iostream>


struct A {
int i;
};


struct B : public A {
int i;
A A;
};


int main() {
B x {1, 2};
std::cout << x.i << '\n';
std::cout << x.B::i << '\n';  // The same as the line above.
std::cout << x.A.i << '\n';
std::cout << x.A::i << '\n';  // Not the same as the line above.
}

Live on Coliru Viewer

Not having a possibility to differentiate with help of ::, which member we want to access, it is impossible to access members declared in a parent class with identical names.