3 回答

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 關注
- 540 瀏覽
添加回答
舉報