c++命名空间的理解与使用using namespace std

C++名称空间的支持是一项C++的特性,当需要组合几个代码且他们还包含相同名称函数时,命名空间就派上用场了,可以将相同的函数封装在不同的命名空间中,这样就可以通过命名空间来指定想要的函数。
按照这种方式,类、函数、变量变是C++编译器的标准组件,都装在名为std的命名空间中。

第一种使用方法:

#include 
int main()
{
//第一种:使用using namespace std语句
using namespace std;
cout << "Come up and C++ me some time";
cout << endl;
cout << "You won regret it!" << endl;
 return 0;
}

不需要在cout、endl前加上std:: ,因为在上方统一定义了。

第二种使用方法,不使用using namespace std语句,using语句意味着std名称空间中的所有名称都可用,这是一种偷懒的做法,不太适用于大型项目。更好的方法是,只使所需的名称可用。

#include 
int main()
{
//第二种:使用std::形式
 std::cout << "Come up and C++ me some time";
 std::cout << std::endl;
 std::cout << "You won regret it!" << std::endl;
  return 0;
}

但上述方法可能较为费劲,需要逐个添加空间名称,这时可以考虑第三种方法,如下:

#include 
int main()
{
using std::cout;
using std::endl;
cout << "Come up and C++ me some time";
cout << endl;
cout << "You won regret it!" << endl;
 return 0;

你可能感兴趣的:(C++,c++)