Question about using namespace

we all know that

"using namespace std;" will disclose all the name in std library

but it is also said that "#include" is like copy the header file in the code file.

Then why do we still need using namespace?

Have we used any namespace when define our own class? we just include our own header file and just use the objects already declared, right?

why there are different mecahnisms for standard and housemade class?

Thanks.
Only because most standard C++ objects, classes and functions are in the std namespace. If you put your classes in a namespace, you would have to use that namespace to get at them, or use the appropriate using namespace statement.

Hope this helps.
Thanks! so, that means I didn't use namespace when define my own class. I see
Well defining a class does not put it in a namespace by default. Consider the following code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// not in a namespace, i.e. in the global namespace
class MyClass1 {
// etc
};

// a namespace
namespace MyNamespace {
   // in a namespace
   class MyClass2 {
      // etc
   };
}

int main()
{
   // access MyClass1 as normal:
   MyClass1 mc1;

   // we need to get the other class via its namespace
   MyNamespace::MyClass2 mc2;

   return 0;
}


Of course, we could also use using namespace:
1
2
3
4
5
6
7
8
9
10
11
12
// classes as above

using namespace MyNamespace;

int main()
{
   MyClass1 mc1;
   // no longer need namespace part: we have used using namespace MyNamespace
   MyClass2 mc2;

   return 0;
}


EDIT:
Have we used any namespace when define our own class?

Not unless you actually put it in a namespace as I did above.

Hope this helps. Read about namespaces here. http://cplusplus.com/doc/tutorial/namespaces/
Last edited on
Topic archived. No new replies allowed.