I decided to play around with namespaces today. I made this function to test if "using namespace" was affected by scope, and it is, which might actually be helpful to me later.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
int function(char n);
int main()
{
int wait;
function('8');
std::cout<<"Hi"<<std::endl;
std::cin>>wait;
}
int function(char n)
{
usingnamespace std;
cout<<"Hello "<<n<<endl;
return 2;
}
But now that I understand that, is there a way to dismiss a namespace? Say, for example, someone has already written a program that called their own namespace globally. I want to add my own code in a section of main, but some of the functions in my namespace collide with theirs. Can I dismiss their namespace for a section, or somehow give my own namespace greater weight?
Thanks for the response Metulburr, I was hoping for a way of cancelling out the other person's namespace for an entire block of code so I don't have to worry about collision, but at least there is a work-around.
Ahh, I just got it. Thanks giblit, I was thinking that if a function is called under the scope of one namespace then all the functions that occur within that function would also be affected by the namespace. Again I end up having to twist my mind around the idea of scope.
Like in this example bellow I thought that since myFunction() is being called under "using namespace him" that it would affect the name() function that myFunction calls internally.
#include <iostream>
namespace me
{
int name()
{
std::cout<<"My name is Chuck\n";
return 1;
}
int myFunction()
{
name();
name();
return name();
}
}
namespace him
{
int name()
{
std::cout<<"What is your name?";
return 0;
}
}
usingnamespace std;
usingnamespace him;
int main()
{
char wait[20];
cout<<"Hi"<<std::endl;
{
usingnamespace me;
myFunction();//I thought a collision would happen when this was called
//because it contains several name() functions internally.
}
name();
cin>>wait;
return 0;
}
Glad that I was wrong, and Thanks, now things are making much more sense.
No problem and you could have a collision like that when you "use" the whole namespace ex "using namespace..." if you try and call name() in your main function it wouldn't know which one..How ever you could just scope to the one you wanted by putting the scope infront
if you put him::name() in your me function then it would call the name function from your him namespace. Just like in your main function you can either call me::name() or him::name() depending on which one you want to call. I don't prefer the "using namespace .." I just scope directly namespace::function()