making your own namespaces

Hello, I'm creating my own namespaces and I had a quick question which I can't seem to answer.

The code below is an example of two namespaces I wrote to group the integer length of each and output it's length using 'distance1::length' and 'distance2::length' in int main()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

#include <iostream>
using namespace std;

namespace distance1{
   int length = 1;
}

namespace distance2{
   int length = 2;
}

int main()
{
cout << distance1::length << endl; //output 1
cout << distance2::length << endl;  //output 2


    return 0;
}


if I were to declare all the elements of distance1 namespace by using namespace distance1 in the scope, would I be able to reference it in a newline with cout without using the conventional distance1::length style?

I've tried using

cout << distance1 << endl;

and get

error: expected primary-expression before ‘<<’ token

What am I doing wrong?

Last edited on
Did you try this?
1
2
using namespace distance1;
cout << length << endl;
Last edited on
Yeah, thanks.

One more quick question, would it be conventional to use using namespace distance1 inside int main() rather than the scope? Both work, I'm just worried about the conventional standard.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
using namespace std;

namespace distance1{
   int length = 1;
}

namespace distance2{
   int length = 2;
}

using namespace distance1;

int main()
{
cout << length << endl; //output1
cout << distance1::length << endl; //output 2
cout << distance2::length << endl;  //output 3


    return 0;
}
Last edited on
I use it in the most local scope that remains convenient in source (.cpp) files. Just avoid using directives in headers.
Topic archived. No new replies allowed.