C++ “使用命名空间 std”有什么用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18914106/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:20:06  来源:igfitidea点击:

What is the use of "using namespace std"?

c++namespacesstdusing

提问by Jarvis

What is the use of using namespace std?

有什么用using namespace std

I'd like to see explanation in Layman terms.

我想看看外行人的解释。

回答by Daniel Daranas

  • using: You are going to use it.
  • namespace: To use what? A namespace.
  • std: The stdnamespace (where features of the C++ Standard Library, such as stringor vector, are declared).
  • using:您将要使用它。
  • 命名空间:使用什么?一个命名空间。
  • stdstd命名空间(声明C++ 标准库的特性,例如stringor vector)。

After you write this instruction, if the compiler sees stringit 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.)

写完这条指令后,如果编译器看到string它就会知道你可能指的是std::string,如果它看到vector,它就会知道你可能指的是std::vector。(当然,前提是您在编译单元中包含了定义它们的头文件。)

If you don'twrite it, when the compiler sees stringor vectorit will not know what you are refering to. You will need to explicitly tell it std::stringor std::vector, and if you don't, you will get a compile error.

如果你写它,当编译器看到string或者vector它不会知道你指的是什么。你需要明确地告诉它std::stringor std::vector,如果你不这样做,你会得到一个编译错误。

回答by Ivaylo Strandjev

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.

当您调用using namespace <some_namespace>;该名称空间中的所有符号时,无需添加名称空间前缀即可可见。例如,符号可以是函数、类或变量。

E.g. if you add using namespace std;you can write just coutinstead of std::coutwhen calling the operator coutdefined in the namespace std.

例如,如果您添加using namespace std;,则可以在调用命名空间中定义的运算符时编写cout而不是编写。std::coutcoutstd

This is somewhat dangerous because namespaces are meant to be used to avoid name collisions and by writing using namespaceyou 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:

这有点危险,因为名称空间旨在用于避免名称冲突并通过编写using namespace您节省一些代码,但失去了这一优势。更好的选择是仅使用特定符号,从而使它们在没有名称空间前缀的情况下可见。例如:

#include <iostream>
using std::cout;

int main() {
  cout << "Hello world!";
  return 0;
}