欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 国际 > 命名空间using namespace std

命名空间using namespace std

2025/10/21 11:34:43 来源:https://blog.csdn.net/Mr_liu888/article/details/141755556  浏览:    关键词:命名空间using namespace std

文章目录

    • 为什么要使用命名空间
    • 如何自主定义命名空间
    • 命名空间的使用方法

为什么要使用命名空间

 命名空间的存在是为了提高代码效率,有效的管理编写代码过程中常用的一些常见关键字

#include <vector>
#include <iostream>
using namespace std;void main() {cout << "hello,world" << endl;}

在上面的一段代码中引入了 <vector>和<iostream>两个头文件,cout函数的具体如何实现的被编写在<iostream>头文件中,但是机器还是不认识cout这个函数,因此在为了让机器知道cout这个名字对应于头文件的cout具体实现,引入标准命名空间std(Standard namespace),这样我们直接就可以访问cout函数了,当然在std中还有很多其他常用的函数和对象,比如cin,endl,...

如何自主定义命名空间

#include <vector>
#include <iostream>
using namespace std;namespace N1 {int a = 8848;int fun() {return 12138;}
}
using namespace N1;void main() {cout << a << endl;cout << fun() << endl;cout << "hello,world" << endl;system("pause");}

这里需要注意的是命名空间的声明需要放在命名空间定义之后

命名空间的使用方法

使用方法大致分为以下三种:

1.声明命名空间名字

使用using namespace 命名空间名引入,如using namespace std;

2.声明命名空间中成员并将成员引入

#include <vector>
#include <iostream>
using std::cout;
using std::endl;void main() {cout << "hello,world" << endl;system("pause");}

3.在使用时直接引入

#include <vector>
#include <iostream>void main() {std::cout << "hello,world" <<std:: endl;system("pause");}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词