After running the following code segment, the output is
Outer.
Inner. Inner.
I know this is about the usage of "namespace", but do not understand why the call of "Inner::message()" print out "Inner". Thanks for explanation.
#include <iostream>
using namespace std;
namespace Outer
{
void message( );
namespace Inner
{
void message( );
}
}
int main( )
{
Outer::message( );
Outer::Inner::message( );
using namespace Outer;
Inner::message( );
return 0;
}
namespace Outer
{
void message( )
{
cout<< "Outer.\n";
}
namespace Inner
{ 开发者_运维技巧
void message( )
{
cout << "Inner.\n";
}
}
}
This makes perfect sense. Your are using namespace Outer
. Inside of namespace Outer
you have two members...
void message();
void Inner::message();
You explicitly scoped into Inner
and called message there. Why would you expect otherwise? Had you not explicitly scoped into Inner
, then it would have called void Outer::message();
.
What other function could Inner::message()
possibly call?
They key is the line using namespace Outer;
- this basically merges the namespace Outer
with the global namespace, which means anything - even other namespaces inside that one - is now directly accessible from the global namespace, as if you were both in global and in the Outer
namespace at once.
By the way: The only other alternative, if you assumed it would not print "Inner.", were for the code not to compile at all.
Inner::message()
prints out "Inner". because of this
namespace Inner
{
void message( )
{
cout << "Inner.\n";
}
}
精彩评论