Namespace and using print fuction

I'm new to using namespace, and im trying to print these values out with print but dont really know how to create the fuction print() to be able to print the values out


#include<iostream>



namespace X{


int var=0;
//void print(int var); trying define fuction called print()

}

namespace Y{

int var=0;
//void print(int var); trying define fuction called print()

}

namespace Z{

int var=0;
//void print(int var); trying define fuction called print()

}



int main()
{
X::var=7;
//std::cout<<X::var;
using namespace Y;
var=9;
print();
{

using Z::var;
using Z::print;
var=11;
print();
}


X::print();

}

You can simply do this for each namespace:
1
2
3
4
5
6
7
8
namespace X{


int var=0;
void print()
{
  std::cout << var;
}


Please use code tags: [code]Your code[/code]
Your main is a little messy.

The using keyword is usually something done outside of functions. The fact that you have using namespace Y; followed by using Z::var; using Z::print; means that you are probably going to have some problems calling the function that you expect. One of the reasons that we use namespaces is so that we can write our own functions or declare global variables without giving them a totally global scope. That means that we can make a sqrt(double x) function of our own and use the one from <cmath> at the same time.
closed account (z05DSL3A)
Stewbond wrote:
The using keyword is usually something done outside of functions.
I tend to disagree with this, using should be used in the smallest scope that is appropriate. The closer to global scope that it is used the more likely you are to run into conflicts.


vega512,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include<iostream>

namespace X
{
    int var = 256;
    void print(int var)
    {
        std::cout <<  "X::print(): "  << var << std::endl;
    }
}

namespace Y
{
    int var = 256;
    void print(int var)
    {
        std::cout <<  "Y::print(): "  << var << std::endl;
    } 
}

namespace Z
{
    int var = 256;
    void print(int var)
    {
        std::cout << "Z::print(): " << var << std::endl;
    } 
}

int main()
{
    using namespace Y;
    var=9;               // Y::var
    print(var);          // Y::Print

    { // 'sub-scope'
        //
        // Bring Z::var and Z::print into this scope
        using Z::var;
        using Z::print;

        var=11;          // Z::var
        print(var);      // Z::print()
    }

    // Use full scope resolution
    X::print(X::var); 
}
Ok thank you guys i was just copying the code how the c++ book had it written but the way you have it makes a lot more sense thank you
Topic archived. No new replies allowed.