What is the use of "using namespace std"?
This question already has an answer here:
std
namespace (where features of the C++ Standard Library, such as string
or vector
, are declared). After you write this instruction, if the compiler sees string
it will know that you may be referring to std::string
, and if it sees vector
, it will know that you may be referring to std::vector
. (Provided that you have included in your compilation unit the header files where they are defined, of course.)
If you don't write it, when the compiler sees string
or vector
it will not know what you are refering to. You will need to explicitly tell it std::string
or std::vector
, and if you don't, you will get a compile error.
When you make a call to using namespace <some_namespace>;
all symbols in that namespace will become visible without adding the namespace prefix. A symbol may be for instance a function, class or a variable.
Eg if you add using namespace std;
you can write just cout
instead of std::cout
when calling the operator cout
defined in the namespace std
.
This is somewhat dangerous because namespaces are meant to be used to avoid name collisions and by writing using namespace
you spare some code, but loose this advantage. A better alternative is to use just specific symbols thus making them visible without the namespace prefix. Eg:
#include <iostream>
using std::cout;
int main() {
cout << "Hello world!";
return 0;
}
链接地址: http://www.djcxy.com/p/29776.html
上一篇: std :: string vs c ++中的字符串
下一篇: “使用命名空间标准”有什么用处?