我是编程初学者,我经常看到很多程序使用前缀std
,如果他们使用的任何std
功能,如std::cout
,std::cin
等我想知道它是什么目的?这只是一种好的编程方式,还是更多的呢?它对编译器有什么区别,或者它是可读性还是什么?谢谢。什么是指定“STD”前缀的需要?
2
A
回答
10
的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;
}
注:有一种包括整个C++命名空间(选项#2)以外的不具有前缀每种类型/方法其他含义std::
文件(特别是如果一个报头内完成)。许多C++程序员避免这种做法,更喜欢#1或#3。
0
12
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和巴兹命名空间。如果您有任何using namespace foo; using namespace baz;
试图调用bar()
将是不明确的。使用命名空间前缀是明确和详细的,有良好的习惯。
1
这是一个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;
避免前缀,如果你能忍受的缺点(名称冲突,不太清楚其中的功能所属的...)。
2
没有人在他们的答案,一个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
声明局部范围(对花括号)内。
相关问题
- 1. 为什么需要std :: minmax_element?
- 2. 什么是注册前缀?
- 3. 什么是表格前缀?
- 4. 什么是http标题,什么时候需要指定它们
- 5. 为什么Spring Security的RoleVoter需要一个前缀?
- 6. 为什么TypeScript需要“this”。 “内部”模块的前缀?
- 7. Swift:Xib文件需要前缀?
- 8. 指定MySQL的表前缀
- 9. 为什么VARCHAR需要长度指定?
- 10. 什么CSS3功能仍然需要供应商前缀?
- 11. 我们什么时候需要用“静态”前缀代表?
- 12. 为什么我需要用x:前缀XML元素?
- 13. 为什么前缀返回没有特定前缀的文档?
- 14. Python字典键/带前缀的值 - 前缀是什么?
- 15. 为什么std :: search需要转发iters
- 16. 锁前缀的范围是什么?
- 17. CSS前缀的用途是什么?
- 18. 什么是r-前缀的函数?
- 19. 成员变量中前缀的重要性是什么?
- 20. 的std :: condition_variable为什么它需要一个std ::互斥
- 21. android的前缀何时需要?
- 22. iOS中的方法需要前缀吗?
- 23. 什么是本地图书馆?什么是绑定的需要?
- 24. !重要的是需要指定宽度
- 25. NS前缀是什么意思?
- 26. pkcs11-tool:为什么我需要指定要加载的模块?
- 27. 为什么std :: fstream类不需要std :: string?
- 28. 如何确定CSS属性是否需要浏览器特定的前缀?
- 29. 自定义标签上的自定义属性是否需要data- *前缀?
- 30. std :: any_cast()和std :: get_if(std :: variant)是否需要将指针作为参数?
因为你的程序将无法不把它编译? – 2011-03-09 00:03:54
另见:http://stackoverflow.com/questions/2218140/what-requires-me-to-declare-using-namespace-std – 2011-03-09 00:05:20