Warm tip: This article is reproduced from stackoverflow.com, please click
c++ language-design

Would replacing ' :: ' with ' . ' create ambiguities in C++?

发布于 2020-03-31 22:54:12

In C++, the operator :: is used to access classes, functions and variables in a namespace or class.

If the language specification used . instead of :: in those cases too like when accessing instance variables/methods of an object then would that cause possible ambiguities that aren't present with ::?

Given that C++ doesn't allow variable names that are also a type name, I can't think of a case where that could happen.

Clarification: I'm not asking why :: was chosen over ., just if it could have worked too?

Questioner
Jimmy R.T.
Viewed
17
Kit. 2020-01-31 19:38

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.