|
-
May 2nd, 2002, 05:33 PM
#1
Thread Starter
Lively Member
Newbie Question
my compiler adds this automatically:
using namespace std;
what is it and what does it do ?
-
May 2nd, 2002, 05:44 PM
#2
namespaces are a C++ feature that allows you to group variables and functions together, but not as closely as they are in classes.
A namespace is simply that: a space in which names exist:
Code:
namespace myspace
{
int i;
float f;
}
i = 4; // doesn't work! wrong scope
myspace::i = 3; // does work, scope resolution operator
This allows you to avoid conflicts of global variables (very useful when you work on a team).
Code:
namespace a
{
int somevar;
}
namespace b
{
int somevar;
}
somevar = 3; // which one?
a::somevar = 5; // this is unambigous
b::somevar = 9;
By convention, all functions/classes/variabels in the C++ runtime library are grouped together in the large namespace std.
Because writing std::... every time may be annoying, there is the using keyword. You can use it to import certain identifiers or a whole namespace to global scope.
Code:
#include <iostream>
using std::cout; // import cout to global scope
cout << "Hello"; // now possible
cout << endl; // not possible, endl is not imported
using namespace std; // import the whole std namespace to global scope
int i;
cin >> i;
cout << i << endl; // possible, all symbols imported
I hope that clears it up some.
All the buzzt
 CornedBee
"Writing specifications is like writing a novel. Writing code is like writing poetry."
- Anonymous, published by Raymond Chen
Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.
-
May 2nd, 2002, 08:45 PM
#3
PowerPoster
Originally posted by CornedBee
namespaces are a C++ feature that allows you to group variables and functions together, but not as closely as they are in classes.
A namespace is simply that: a space in which names exist:
[code]
namespace myspace
{
int i;
float f;
}
Just curious, what if declared a variable called "i" outside the namespace myspace? I hope it won't give you any error and will let you use that ouside i.
-
May 2nd, 2002, 08:52 PM
#4
Fanatic Member
you can still use it
if you had
Code:
int i;
void blah(){
int i;
}
you can access the global i like
Visit www.fragblast.com
Gaming, forums, and a online RPG/Battle system
(__Flagg) DOT NET? is this a Hindi Dating service?
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|