C++ 诞生于 1983 年,是 C 语言"加上类"的产物,但远不止如此:它同时支持面向过程、面向对象和泛型编程,是操作系统、游戏引擎、高性能服务器的主流语言。如果你已经会 C,学 C++ 就像换了一把带配件的瑞士军刀——本文带你认识刀刃和新增的每一件工具。
1. 从 C 到 C++:多了什么
C 的核心是"过程":函数 + 数据。C++ 在这之上补充了三大件:
- 面向对象:class、继承、多态,让代码贴近现实模型。
- 泛型编程:模板(template),一套算法适配所有类型。
- 标准库:STL 容器、算法、字符串,告别手写链表和 strcpy。
2. 第一个 C++ 程序
和 C 相比,头文件去掉了 .h,输入输出换成了 iostream:
#include <iostream>
int main() {
std::cout << "Hello, C++!" << std::endl;
return 0;
}
用 g++ hello.cpp -o hello 编译(注意是 g++ 而非 gcc),运行输出 Hello, C++!。看不懂 std:: 没关系,下一节解释。
3. 输入输出:cin 与 cout
C 的 printf/scanf 靠格式串匹配,类型写错就出 bug;C++ 的 cin/cout 靠类型推断,更安全直观:
#include <iostream>
#include <string>
using namespace std;
int main() {
string name;
int age;
cout << "姓名: ";
cin >> name;
cout << "年龄: ";
cin >> age;
cout << name << " 明年 " << age + 1 << " 岁" << endl;
return 0;
}
using namespace std; 让我们少敲 std::,但头文件里别这么写,容易污染全局命名空间。
4. 三个新特性速览
bool 类型
C 用 int 冒充真假,C++ 有真正的 bool,配合 true/false 使用,语义更清晰。
引用
引用是变量的"别名",比指针更安全:
int x = 42;
int& ref = x; // ref 是 x 的别名
ref = 100; // 等价于 x = 100
cout << x; // 输出 100
函数重载
同名函数靠参数类型区分,C 做不到,C++ 可以:
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
// add(1, 2) 调 int 版,add(1.5, 2.5) 调 double 版
5. 从 C 迁移速查表
| C 写法 | C++ 写法 | 说明 |
|---|---|---|
| #include <stdio.h> | #include <iostream> | 头文件无 .h |
| printf / scanf | cout / cin | 类型安全,不易写错 |
| char s[] + strcpy | std::string | 自动管理内存 |
| malloc / free | new / delete | 构造与析构配对 |
| typedef struct | class | 封装 + 成员方法 |
💡 学 C++ 最大的误区是"把 C++ 当 C 写"。从第一行代码就用std::string、cin/cout、vector,让标准库帮你管理内存,比纠结指针细节重要得多。