假设我有不同的命名空间,比如苹果命名空间和橙子命名空间,但是这两个命名空间都包含一个名为myfunction()的函数。
当我在主函数中调用myfunction()时会发生什么?
当我在主函数中调用myfunction()时会发生什么?
这正是命名空间的用途所在。
在您的main()
函数中,或一般来说在全局命名空间中,您将能够选择要调用哪个myfunction
:
int main()
{
apple::myfunction(); // call the version into the apple namespace
orange::myfunction(); // call the orange one
myfunction(); // error: there is no using declaration / directive
}
如果存在一个using指示符(using namespace apple
)或者一个using声明(using apple::myfunction
),则主函数的最后一行会调用命名空间apple
中的版本。如果两个myfunction
版本都在作用域内,则最后一行会再次产生错误,因为在这种情况下必须指定要调用哪个函数。
using namespace apple
和 using namespace orange
这样的东西呢?我想这就是完整答案的最后一部分了。 - Timo::myfunction();
。该语句的作用是调用未命名空间中的函数。 - Mr Listernamespace Gandalf{
namespace Frodo{
bool static hasMyPrecious(){ // _ZN7Gandalf5FrodoL13hasMyPreciousEv
return true;
}
};
bool static hasMyPrecious(){ // _ZN7GandalfL13hasMyPreciousEv
return true;
}
};
namespace Sauron{
bool static hasMyPrecious(){ // _ZN5SauronL13hasMyPreciousEv
return true;
}
};
bool hasMyPrecious(){ // _Z13hasMyPreciousv
return true;
}
int main()
{
if( Gandalf::Frodo::hasMyPrecious() || // _ZN7Gandalf5FrodoL13hasMyPreciousEv
Gandalf::hasMyPrecious() || // _ZN7GandalfL13hasMyPreciousEv
Sauron::hasMyPrecious() || // _ZN5SauronL13hasMyPreciousEv
hasMyPrecious()) // _Z13hasMyPreciousv
return 0;
return 1;
}