简单C++4 分钟1,247 字

头文件与命名空间

每一个 C++ 程序开头都有 #include <iostream> 和 using namespace std;。这两行到底做了什么?为什么有时写 std::cout,有时直接写 cout?这一节讲清楚。

头文件:把"已写好的代码"引进来

C++ 把常用功能按主题拆成头文件​​,用 #include 引入。#include 是预处理指令​​,在编译真正开始之前,会把头文件的内容原样"粘贴"到这一行位置。

cpp
#include <iostream>    // 提供 cin / cout / endl
#include <cmath>       // 提供 sqrt / pow / abs
#include <algorithm>   // 提供 sort / max / min
#include <string>      // 提供 std::string
#include <vector>      // 提供 std::vector

尖括号 < > 与双引号 " " 的区别

写法 查找顺序 用途
#include <stdio.h> 只在系统目录查找 标准库
#include "myheader.h" 先找当前目录,再找系统目录 自己写的头文件

C 与 C++ 头文件的区别

C++ 标准库把 C 的头文件重新包装,去掉了 .h 并加了 c 前缀:

C 风格(仍可用) C++ 风格(推荐)
#include <stdio.h> #include <cstdio>
#include <math.h> #include <cmath>
#include <string.h> #include <cstring>

两者功能相同,但 C++ 版本会把名字放进 std 命名空间,更规范。

常见的"偷懒"写法

竞赛中经常看到一个万能头文件:

cpp
#include <bits/stdc++.h>   // 绝大多数标准库一次引入(GCC 特有)

它能省事,但不是 C++ 标准​​,换编译环境可能报错。平时练习建议按需引入,清楚每个函数来自哪个头文件。

命名空间:解决"重名"问题

<iostream> 里定义了 cout、cin、endl,但别的库也可能定义同名的东西。C++ 用命名空间(namespace)​ 来隔离:

cpp
#include <iostream>

int main() {
    std::cout << "hello" << std::endl;   // 明确指定:来自 std 命名空间
    return 0;
}

std 是 C++ 标准库的命名空间。不写前缀会报错:

cpp
cout << "hello";   // 编译错误:找不到 cout

using namespace std; 做了什么

这一行把 std 命名空间里的所有名字"释放"到全局,于是可以直接写 cout:

cpp
#include <iostream>
using namespace std;

int main() {
    cout << "hello" << endl;   // 不需要 std:: 前缀了
    return 0;
}

三种写法对比

cpp
// 写法一:全部释放(竞赛常用,代码简洁)
using namespace std;
cout << x;

// 写法二:每次加前缀(最安全,工程常用)
std::cout << x;

// 写法三:只释放用到的名字(折中)
using std::cout;
using std::endl;
cout << x << endl;

using namespace std 的隐患

在大型工程里,std 有几百个名字,全部释放容易和自己的变量、函数撞名:

cpp
#include <iostream>
using namespace std;

int max = 100;    // 编译错误:与 std::max 冲突!

int main() { ... }

这就是为什么教材和竞赛模板常用它(比赛代码短、冲突概率低),而**工业级项目通常显式写 std::**​​。

一个完整的程序拆解

cpp
#include <iostream>      // ① 引入输入输出功能
using namespace std;     // ② 打开标准命名空间

int main() {             // ③ 程序入口,返回 int
    int a, b;
    cin >> a >> b;       // ④ 从 std 命名空间取 cin
    cout << a + b << endl;
    return 0;            // ⑤ 返回 0 表示正常结束
}

自定义命名空间

命名空间不止标准库能用,自己也可以定义,用来组织代码:

cpp
#include <iostream>

namespace mymath {
    int add(int a, int b) { return a + b; }
    const int MAXN = 100000;
}

int main() {
    std::cout << mymath::add(1, 2) << std::endl;  // 用 mymath:: 访问
    std::cout << mymath::MAXN << std::endl;
    return 0;
}

常见错误

  • **忘记 using 又忘加 std::**​​:cout 未定义,编译报错。
  • 头文件写在 main 里面​​:#include 必须写在文件顶部。
  • **在头文件里写 using namespace std;**​​:会污染所有引入它的文件,实践中强烈不推荐。
  • 以为 <bits/stdc++.h> 处处可用​​:MSVC 等编译器不支持。

小结

#include 负责"引入能力",namespace 负责"隔离名字"。std::cout 是全限定写法(最安全),using namespace std; 是竞赛里图方便的写法。理解这两行,就不会再对着"cout 未定义"的报错发呆了。

同类知识点