为什么C ++需要范围解析运算符?

为什么C ++具有::运算符,而不是.为此目的使用运算符?Java没有单独的运算符,并且运行良好。C ++和Java之间有什么区别,这意味着C ++需要单独的运算符才能进行解析?


我唯一的猜测是::出于优先级原因而需要这样做,但是我不知道为什么它需要具有比更高的优先级.。我能想到的唯一情况是


a.b::c;

将被解析为


a.(b::c);

,但我想不出任何这样的语法仍然合法的情况。


也许只是“他们做不同的事情,所以他们看起来也不一样”的情况。但这并不能解释为什么::优先级高于.。


largeQ
浏览 518回答 3
3回答

呼唤远方

为什么C ++不使用.它在何处使用::,是因为这是语言的定义方式。一个合理的原因可能是,使用::a如下所示的语法引用全局名称空间:int a = 10;namespace M{&nbsp; &nbsp; int a = 20;&nbsp; &nbsp; namespace N&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;int a = 30;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;void f()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int x = a; //a refers to the name inside N, same as M::N::a&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int y = M::a; //M::a refers to the name inside M&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int z = ::a; //::a refers to the name in the global namespace&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; std::cout<< x <<","<< y <<","<< z <<std::endl; //30,20,10&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; }}在线演示我不知道Java如何解决这个问题。我什至不知道在Java中是否有全局名称空间。在C#中,您使用语法来引用全局名称global::a,这意味着即使C#也具有::运算符。但我想不出任何这样的语法仍然合法的情况。谁说语法a.b::c不合法?考虑以下类:struct A{&nbsp; &nbsp; void f() { std::cout << "A::f()" << std::endl; }};struct B : A{&nbsp; &nbsp; void f(int) { std::cout << "B::f(int)" << std::endl; }};现在看这个(ideone):B b;b.f(10); //okb.f();&nbsp; &nbsp;//error - as the function is hiddenb.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 resolutionideone上的演示
打开App,查看更多内容
随时随地看视频慕课网APP