What are the complete legal entities that can be put in a namespace?
I'm learning C++ now. What are the complete legal entities that can be put in a namespace?
Legal entities here means valid members of a namespace
Oh, this is a real question. I'm coming from .net and I have the .net mindset.
Any code can be put inside namespace.
However main()
function must be at global namespace. It cannot be put inside user-defined namespace.
namespace userns
{
int main()
{
return 0;
}
}
This program wouldn't compile link : http://www.ideone.com/k6SPc
Its because userns::main()
will not be considered entry-point of the program; it became just like any other user function, not the standard main()
. To compile it successfull, you've to add main()
at global namespace:
namespace userns
{
int main()
{
return 0;
}
}
int main()
{
return 0;
}
This will compile link now : http://www.ideone.com/76Ynu
Anything can be put in a namespace (which is legal for C++
, of course).
Actually, everything is in some namespace - the global namespace, if not specified.
Everything can be put in namespace
except few "entities", which will not compile.
(1) Globally overloaded operator new
and operator delete
namespace N
{
void* operator new (size_t size) // error
{ ... }
}
(2) Definition of the constructs which are declared in outer scope of the namespace
; for example you have a class A
declared globally then you cannot define its method inside your namespace N
. In the same way, if you have method declared in a namespace N
then you cannot put its definition inside namespace N::Nested
(i.e. Nested
is a namespace inside N
).
//file
struct A {
void foo ();
static int i;
};
namespace N
{
int A::i = 0; // error
void A::foo() // error
{}
}
Demo: this is not allowed.
I remember at least these 2 restrictions from my experience. Don't know about specs.
精彩评论