C++ 命名空间的using声明
C++中,老师上课说的一直有一句:
using namespace std;
,不过他是什么意思,其实也就是一个命名空间的概念,概念这东西不多说(Primer 74页)
我们为什么要使用命名空间,不使用会有什么麻烦。 这里我们看一段代码:
1#include <iostream>
2
3int main()
4{
5 std::cout << "Enter two numbers:" << std::endl;
6 int v1 = 0, v2 = 0;
7 std::cin >> v1 >> v2;
8 std::cout << "The sum of " << v1 << " and " << v2 << " is " << v1 + v2 << std::endl;
9
10 return 0;
11}
12
这是一个没有使用命名空间的代码,可以看到本来我们写的cout
、cin
中前面都有了std::
,但我们加上using std::cin
和using std::cout
之后就没有这个麻烦了,而using namespace std
则是属于永除后患,不然的话,用到什么写什么,其实也是可以的。
最简单的来说,like that:
1#include <iostream>
2
3using namespace std;
4int main()
5{
6 cout << "This is a C++ program.\n";
7 return 0;
8}
9
评论 (0)