【发布时间】:2011-07-11 12:36:46
【问题描述】:
我是编程的初学者,我经常看到许多程序使用前缀std,如果他们使用任何std 函数,如std::cout、std::cin 等。我想知道它的目的是什么?它只是一种良好的编程方式还是还有更多?它对编译器有什么影响,还是可读性?谢谢。
【问题讨论】:
-
因为你的程序没有它就无法编译?
我是编程的初学者,我经常看到许多程序使用前缀std,如果他们使用任何std 函数,如std::cout、std::cin 等。我想知道它的目的是什么?它只是一种良好的编程方式还是还有更多?它对编译器有什么影响,还是可读性?谢谢。
【问题讨论】:
没有人在他们的回答中提到 using namespace foo 语句可以放在函数体内,从而减少其他范围内的命名空间污染。
例如:
// This scope not affected by using namespace statement below.
void printRecord(...)
{
using namespace std;
// Frequent use of std::cout, io manipulators, etc...
// Constantly prefixing with std:: would be tedious here.
}
class Foo
{
// This scope not affected by using namespace statement above.
};
int main()
{
// This scope not affected either.
}
您甚至可以将using namespace foo 语句放在本地范围内(一对花括号)。
【讨论】:
STL 类型和函数在名为std 的命名空间中定义。 std:: 前缀用于使用不完全包含 std 命名空间的类型。
选项1(使用前缀)
#include <iostream>
void Example() {
std::cout << "Hello World" << std::endl;
}
选项 #2(使用命名空间)
#include <iostream>
using namespace std;
void Example() {
cout << "Hello World" << endl;
}
选项 #3(单独使用类型)
#include <iostream>
using std::cout;
using std::endl;
void Example() {
cout << "Hello World" << endl;
}
注意:除了不必在每个类型/方法前面加上 std::(尤其是在头文件中完成时)之外,包含整个 C++ 命名空间(选项 #2)还有其他含义。许多 C++ 程序员避免这种做法,而更喜欢 #1 或 #3。
【讨论】:
std::swap 的首选,因为using std::swap; swap(a,b); 是确保您获得 ADL 重载的方法 swap(如果存在),而且很无聊std::swap 如果没有。 std::swap 可以一次专门用于用户定义的类,但对于用户定义的类模板,ADL 是提供自定义交换的唯一合法方式。不过,移动语义可以让这个问题消失,也许这种使用std::swap 的方式可以在 C++0x 中改变。
std 命名空间中的某些东西不在 STL 中。)
标准命名空间的简称。
你可以使用:
using namespace std
如果你不想继续使用 std::cout 而只使用 cout
【讨论】:
std:: 优于 using namespace std
C++ 有命名空间的概念。
namespace foo {
int bar();
}
namespace baz {
int bar();
}
这两个函数可以共存而不冲突,因为它们位于不同的命名空间中。
大多数标准库函数和类都位于“std”命名空间中。访问例如cout,您需要按照优先顺序执行以下操作之一:
std::cout << 1;using std::cout; cout << 1;using namespace std; cout << 1;您应该避免使用using 的原因已通过上述 foo 和 baz 命名空间进行了说明。如果您有using namespace foo; using namespace baz;,那么任何尝试调用bar() 都是模棱两可的。使用命名空间前缀是明确而准确的,是一个好习惯。
【讨论】:
这是一个名为命名空间的 C++ 功能:
namespace foo {
void a();
}
// ...
foo::a();
// or:
using namespace foo;
a(); // only works if there is only one definition of `a` in both `foo` and global scope!
优点是,可能有多个名为a 的函数——只要它们位于不同的命名空间中,就可以明确地使用它们(即foo::a()、another_namespace::a())。为此,整个 C++ 标准库位于 std 中。
使用using namespace std; 来避免前缀,如果你能忍受缺点(名称冲突,不太清楚函数属于哪里,...)。
【讨论】: