命名空间using namespace std

文章目录

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

为什么要使用命名空间

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

cpp 复制代码
#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,...

如何自主定义命名空间

cpp 复制代码
#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.声明命名空间名字

cpp 复制代码
使用using namespace 命名空间名引入,如using namespace std;

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

cpp 复制代码
#include <vector>
#include <iostream>
using std::cout;
using std::endl;

void main() {

    cout << "hello,world" << endl;
    system("pause");
    
    }
    

3.在使用时直接引入

cpp 复制代码
#include <vector>
#include <iostream>

void main() {

    std::cout << "hello,world" <<std:: endl;
    system("pause");
    
    }
    
相关推荐
lihongli000几秒前
【工程实战】Win11 + Ubuntu20.04 + Ubuntu24.04 三系统长期稳定安装方案(含避坑指南)
开发语言
Ka1Yan2 分钟前
[数组] - 代码随想录(2-6)
数据结构·算法·leetcode
黄宝康18 分钟前
sublimetext 运行python程序
开发语言·python
m0_7482500328 分钟前
C++ 官方文档与标准
开发语言·c++
zh_xuan43 分钟前
kotlin 类继承的语法2
开发语言·kotlin
漫随流水1 小时前
leetcode算法(104.二叉树的最大深度)
数据结构·算法·leetcode·二叉树
matlabgoodboy1 小时前
程序代做python代编程matlab定制代码编写C++代写plc设计java帮做
c++·python·matlab
机器学习之心HML1 小时前
鲸鱼算法(WOA)优化Kriging模型
算法
DYS_房东的猫1 小时前
《 C++ 零基础入门教程》第6章:模板与 STL 算法 —— 写一次,用万次
开发语言·c++·算法
Tim_101 小时前
【算法专题训练】37、前缀树&二叉树
算法