3 回答
![?](http://img1.sycdn.imooc.com/545867280001ed6402200220-100-100.jpg)
TA贡献1856条经验 获得超11个赞
为什么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上的演示
- 3 回答
- 0 关注
- 517 浏览
添加回答
举报