为什么 C++ 不使用.
它使用的地方::
,是因为这就是语言的定义方式。一个可能的原因是,使用::a
如下所示的语法来引用全局命名空间:
int a = 10;
namespace M
{
int a = 20;
namespace N
{
int a = 30;
void f()
{
int x = a; //a refers to the name inside N, same as M::N::a
int y = M::a; //M::a refers to the name inside M
int z = ::a; //::a refers to the name in the global namespace
std::cout<< x <<","<< y <<","<< z <<std::endl; //30,20,10
}
}
}
在线演示
我不知道Java如何解决这个问题。我什至不知道在 Java 中是否有全局命名空间。在 C# 中,您使用语法来引用全局名称global::a
,这意味着即使 C# 也有::
运算符。
但我想不出这样的语法在任何情况下都是合法的。
谁说类似语法a.b::c
不合法?
考虑这些类:
struct A
{
void f() { std::cout << "A::f()" << std::endl; }
};
struct B : A
{
void f(int) { std::cout << "B::f(int)" << std::endl; }
};
现在看到这个(ideone):
B b;
b.f(10); //ok
b.f(); //error - as the function is hidden
b.f()
不能这样调用,因为该函数是隐藏的,并且 GCC 会给出以下错误消息:
error: no matching function for call to ‘B::f()’
为了调用b.f()
(或者更确切地说A::f()
),您需要范围解析运算符:
b.A::f(); //ok - explicitly selecting the hidden function using scope resolution
在 ideone 演示