C++ 入门与核心语法详解
本文介绍了 C++ 的发展历史、版本更新及参考文档资源,详细阐述了命名空间、输入输出流、缺省参数、函数重载、引用、内联函数及空指针常量等核心概念。通过代码示例展示了变量作用域管理、内存效率优化及类型安全实践,适合初学者系统掌握 C++ 编程基础与进阶技巧。

本文介绍了 C++ 的发展历史、版本更新及参考文档资源,详细阐述了命名空间、输入输出流、缺省参数、函数重载、引用、内联函数及空指针常量等核心概念。通过代码示例展示了变量作用域管理、内存效率优化及类型安全实践,适合初学者系统掌握 C++ 编程基础与进阶技巧。


微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online
将 Markdown(GFM)转为 HTML 片段,浏览器内 marked 解析;与 HTML转Markdown 互为补充。 在线工具,Markdown转HTML在线工具,online
将 HTML 片段转为 GitHub Flavored Markdown,支持标题、列表、链接、代码块与表格等;浏览器内处理,可链接预填。 在线工具,HTML转Markdown在线工具,online
通过删除不必要的空白来缩小和压缩JSON。 在线工具,JSON 压缩在线工具,online
C++ 的起源可以追溯到 1979 年,当时 Bjarne Stroustrup(本贾尼·斯特劳斯特卢普)在贝尔实验室从事计算机科学和软件工程的研究工作。面对项目中复杂的软件开发任务,特别是模拟和操作系统的开发工作,他感受到了现有语言(如 C 语言)在表达能力、可维护性和可扩展性方面的不足。
1983 年,Bjarne Stroustrup 在 C 语言的基础上添加了面向对象编程的特性,设计出了 C++ 语言的雏形,此时的 C++ 已经有了类、封装、继承等核心概念,为后来的面向对象编程奠定了基础。这一年该语言被正式命名为 C++。
在随后的几年中,C++ 在学术界和工业界的应用逐渐增多。一些大学和研究所开始将 C++ 作为教学和研究的首选语言,而一些公司也开始在产品开发中尝试使用 C++。这一时期,C++ 的标准库和模板等特性也得到了进一步完善和发展。
C++ 的标准化工作于 1989 年开始,并成立了一个 ANSI 和 ISO(International Standards Organization)国际标准化组织的联合标准化委员会。1994 年标准化委员会提出了第一个标准化草案。在该草案中,委员会在保持斯特劳斯特卢普最初定义的所有特征的同时,还增加了部分新特征。
在完成 C++ 标准化的第一个草案后不久,STL(Standard Template Library)是惠普实验室开发的一系列软件的统称。它是由 Alexander Stepanov、Meng Lee 和 David R Musser 在惠普实验室工作时所开发出来的。在通过了标准化第一个草案之后,联合标准化委员会投票并通过了将 STL 包含到 C++ 标准中的提议。STL 对 C++ 的扩展超出 C++ 的最初定义范围。虽然在标准中增加 STL 是个很重要的决定,但也因此延缓了 C++ 标准化的进程。
1997 年 11 月 14 日,联合标准化委员会通过了该标准的最终草案。1998 年,C++ 的 ANSI/ISO 标准被投入使用。
| 时间 | 版本 | 主要内容 |
|---|---|---|
| 1998 年 | C++98 | 首个官方版本,引入 STL(标准模板库) |
| 2003 年 | C++03 | 修复 C++98 漏洞,增强稳定性和兼容性 |
| 2011 年 | C++11 | 革命性更新:lambda、右值引用、智能指针、多线程支持等 |
| 2014 年 | C++14 | 扩展 C++11:泛型 lambda 返回值推导、二进制字面常量等 |
| 2017 年 | C++17 | 新增 if constexpr、折叠表达式,改进 string、filesystem 等 |
| 2020 年 | C++20 | 里程碑更新:协程(Coroutines)、概念(Concepts)、模块化(Modules)等 |
| 2023 年 | C++23 | 小版本更新:if consteval、flat_map、import std 等 |
| 2026 年 | C++26 | 制定中 |
说明:第一个链接不是 C++ 官方文档,标准也只更新到 C++11,但是以头文件形式呈现,内容比较易看好懂。后两个链接分别是 C++ 官方文档的中文版和英文版,信息很全,更新到了最新的 C++ 标准,但是相比第一个不那么易看;几个文档各有优势,我们结合着使用。
TIOBE 排行榜是根据互联网上有经验的程序员、课程和第三方厂商的数量,并使用搜索引擎(如 Google、Bing、Yahoo!)以及 Wikipedia、Amazon、YouTube 和 Baidu(百度)统计出排名数据,只是反映某个编程语言的热度程度,并不能说明一门编程语言好不好,或者一门语言所编写的代码数量多少。
C++ 的应用领域服务器端、游戏(引擎)、机器学习引擎、音视频处理、嵌入式软件、电信设备、金融应用、基础库、操作系统、编译器、基础架构、基础工具、硬件交互等方面都有。
C++ 兼容 C 语言绝大多数的语法,所以 C 语言实现的 helloworld 依旧可以运行,C++ 中需要将定义文件代码后缀改为.cpp,vs 编译器看到是.cpp 就会调用 C++ 编译器编译,linux 下要用 g++ 编译,不再是 gcc。
// test.cpp
#include<stdio.h>
int main() {
printf("hello world\n");
return 0;
}
当然 C++ 有一套自己的输入输出,严格说 C++ 版本的 helloworld 应该是这样写的。
// test.cpp
// 这里的 std cout 等我们都看不懂,没关系,下面我们会依次讲解
#include<iostream>
using namespace std;
int main() {
cout << "hello world\n" << endl; // 这里的 endline 相当于换行的作用
return 0;
}
在 C/C++ 中,变量、函数和后面要学到的类都是大量存在的,这些变量、函数和类的名称将都存在于全局作用域中,可能会导致很多冲突。使用命名空间的目的是对标识符的名称进行本地化,以避免命名冲突或名字污染,namespace 关键字的出现就是针对这种问题的。 C 语言项目类似下面程序这样的命名冲突是普遍存在的问题,C++ 引入 namespace 就是为了更好的解决这样的问题。
#include<stdio.h>
#include<stdlib.h>
int rand = 10;
int main(){
// 编译报错:error C2365: 'rand': 重定义;以前的定义是'函数'
printf("%d\n", rand);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
// 1. 正常的命名空间定义
// fnx 是命名空间的名字,一般开发中是用项目名字做命名空间名。
namespace fnx {
// 命名空间中可以定义变量/函数/类型
int rand = 10;
int Add(int left, int right) {
return left + right;
}
struct Node {
struct Node* next;
int val;
};
}
int main() {
// 这里默认是访问的是全局的 rand 函数指针
printf("%p\n", rand);
// 这里指定 bit 命名空间中的 rand
printf("%d\n", fnx::rand);
return 0;
}
// 2. 命名空间可以嵌套
namespace fnx {
// czx 的代码
namespace czx {
int rand = 1;
int Add(int left, int right) {
return left + right;
}
}
// lgh 的代码
namespace lgh {
int rand = 2;
int Add(int left, int right) {
return (left + right)*10;
}
}
}
int main() {
printf("%d\n", fnx::czx::rand);
printf("%d\n", fnx::lgh::rand);
printf("%d\n", fnx::czx::Add(1, 2));
printf("%d\n", fnx::lgh::Add(1, 2));
return 0;
}
多文件中可以定义同名 namespace,他们会默认合并到一起,就像同一个 namespace 一样。
// Stack.h
#pragma once
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#include<assert.h>
namespace fnx {
typedef int STDataType;
typedef struct Stack {
STDataType* a;
int top;
int capacity;
}ST;
void STInit(ST* ps, int n);
void STDestroy(ST* ps);
void STPush(ST* ps, STDataType x);
void STPop(ST* ps);
STDataType STTop(ST* ps);
int STSize(ST* ps);
bool STEmpty(ST* ps);
}
// Stack.cpp
#include"Stack.h"
namespace fnx {
void STInit(ST* ps, int n) {
assert(ps);
ps->a = (STDataType*)malloc(n * sizeof(STDataType));
ps->top = 0;
ps->capacity = n;
}
// 栈顶
void STPush(ST* ps, STDataType x) {
assert(ps);
// 满了,扩容
if (ps->top == ps->capacity) {
printf("扩容\n");
int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
STDataType* tmp = (STDataType*)realloc(ps->a, newcapacity * sizeof(STDataType));
if (tmp == NULL) {
perror("realloc fail");
return;
}
ps->a = tmp;
ps->capacity = newcapacity;
}
ps->a[ps->top] = x;
ps->top++;
}
//...
}
// Queue.h
#pragma once
#include<stdlib.h>
#include<stdbool.h>
#include<assert.h>
namespace fnx {
typedef int QDataType;
typedef struct QueueNode {
int val;
struct QueueNode* next;
}QNode;
typedef struct Queue {
QNode* phead;
QNode* ptail;
int size;
}Queue;
void QueueInit(Queue* pq);
void QueueDestroy(Queue* pq);
// 入队列
void QueuePush(Queue* pq, QDataType x);
// 出队列
void QueuePop(Queue* pq);
QDataType QueueFront(Queue* pq);
QDataType QueueBack(Queue* pq);
bool QueueEmpty(Queue* pq);
int QueueSize(Queue* pq);
}
// Queue.cpp
#include"Queue.h"
namespace fnx {
void QueueInit(Queue* pq) {
assert(pq);
pq->phead = NULL;
pq->ptail = NULL;
pq->size = 0;
}
// ...
}
// test.cpp
#include"Queue.h"
#include"Stack.h"
// 全局定义了一份单独的 Stack
typedef struct Stack {
int a[10];
int top;
}ST;
void STInit(ST* ps){}
void STPush(ST* ps, int x){}
int main() {
// 调用全局的
ST st1;
STInit(&st1);
STPush(&st1, 1);
STPush(&st1, 2);
printf("%d\n", sizeof(st1));
// 调用 fnx namespace 的
fnx::ST st2;
printf("%d\n", sizeof(st2));
fnx::STInit(&st2);
fnx::STPush(&st2, 1);
fnx::STPush(&st2, 2);
return 0;
}
编译查找一个变量的声明/定义时,默认只会在局部或者全局查找,不会到命名空间里面去查找。所以下面程序会编译报错。所以我们要使用命名空间中定义的变量/函数,有三种方式:
#include<stdio.h>
namespace N {
int a = 0;
int b = 1;
}
int main() {
// 编译报错:error C2065: 'a': 未声明的标识符
printf("%d\n", a);
return 0;
}
// 指定命名空间访问
int main() {
printf("%d\n", N::a);
return 0;
}
// using 将命名空间中某个成员展开
using N::b;
int main() {
printf("%d\n", N::a);
printf("%d\n", b);
return 0;
}
// 展开命名空间中全部成员
using namespace N;
int main() {
printf("%d\n", a);
printf("%d\n", b);
return 0;
}
#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
using namespace std;
int main() {
int a = 0;
double b = 0.1;
char c = 'x';
cout << a << " " << b << " " << c << endl;
std::cout << a << " " << b << " " << c << std::endl;
scanf("%d%lf", &a, &b);
printf("%d %lf\n", a, b);
// 可以自动识别变量的类型
cin >> a;
cin >> b >> c;
cout << a << endl;
cout << b << " " << c << endl;
return 0;
}
#include<iostream>
using namespace std;
int main() {
// 在 io 需求比较高的地方,如部分大量输入的竞赛题中,加上以下 3 行代码
// 可以提高 C++IO 效率
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return 0;
}
#include <iostream>
#include <assert.h>
using namespace std;
void Func(int a = 0) {
cout << a << endl;
}
int main() {
Func(); // 没有传参时,使用参数的默认值
Func(10); // 传参时,使用指定的实参
return 0;
}
#include<iostream>
using namespace std;
// 全缺省
void Func1(int a = 10, int b = 20, int c = 30) {
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "c = " << c << endl << endl;
}
// 半缺省
void Func2(int a, int b = 10, int c = 20) {
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "c = " << c << endl << endl;
}
int main() {
Func1();
Func1(1);
Func1(1, 2);
Func1(1, 2, 3);
Func2(100);
Func2(100, 200);
Func2(100, 200, 300);
return 0;
}
// Stack.h
#include <iostream>
#include <assert.h>
using namespace std;
typedef int STDataType;
typedef struct Stack {
STDataType* a;
int top;
int capacity;
}ST;
void STInit(ST* ps, int n = 4);
// Stack.cpp
#include"Stack.h"
// 缺省参数不能声明和定义同时给
void STInit(ST* ps, int n) {
assert(ps && n > 0);
ps->a = (STDataType*)malloc(n * sizeof(STDataType));
ps->top = 0;
ps->capacity = n;
}
// test.cpp
#include"Stack.h"
int main() {
ST s1;
STInit(&s1); // 确定知道要插入 1000 个数据,初始化时一把开好,避免扩容
ST s2;
STInit(&s2, 1000);
return 0;
}
C++ 支持在同一作用域中出现同名函数,但是要求这些同名函数的形参不同,可以是参数个数不同或者类型不同。这样 C++ 函数调用就表现出了多态行为,使用更灵活。C 语言是不支持同一作用域中出现同名函数的。
#include<iostream>
using namespace std;
// 1、参数类型不同
int Add(int left, int right) {
cout << "int Add(int left, int right)" << endl;
return left + right;
}
double Add(double left, double right) {
cout << "double Add(double left, double right)" << endl;
return left + right;
}
// 2、参数个数不同
void f() {
cout << "f()" << endl;
}
void f(int a) {
cout << "f(int a)" << endl;
}
// 3、参数类型顺序不同
void f(int a, char b) {
cout << "f(int a,char b)" << endl;
}
void f(char b, int a) {
cout << "f(char b, int a)" << endl;
}
// 返回值不同不能作为重载条件,因为调用时也无法区分
//void fxx() {}
//int fxx() { return 0; }
// 下面两个函数构成重载
// f() 但是调用时,会报错,存在歧义,编译器不知道调用谁
void f1() {
cout << "f()" << endl;
}
void f1(int a = 10) {
cout << "f(int a)" << endl;
}
int main() {
Add(10, 20);
Add(10.1, 20.2);
f();
f(10);
f(10, 'a');
f('a', 10);
return 0;
}
引用不是新定义一个变量,而是给已存在变量取了一个别名,编译器不会为引用变量开辟内存空间,它和它引用的变量共用同一块内存空间。比如:水壶传中李逵,宋江叫"铁牛",江湖上人称"黑旋风";林冲,外号豹子头; 类型&引用别名=引用对象;C++ 中为了避免引入太多的运算符,会复用 C 语言的一些符号,比如前面的<<和>>,这里引用也和取地址使用了同一个符号&,大家使用方法角度区分就可以。(吐槽一下,这个问题其实挺坑的,个人觉得用更多符号反而更好,不容易混淆)
#include<iostream>
using namespace std;
int main() {
int a = 0;
// 引用:b 和 c 是 a 的别名
int& b = a;
int& c = a;
// 也可以给别名 b 取别名,d 相当于还是 a 的别名
int& d = b;
++d; // 这里取地址我们看到是一样的
cout << &a << endl;
cout << &b << endl;
cout << &c << endl;
cout << &d << endl;
return 0;
}
#include<iostream>
using namespace std;
int main() {
int a = 10;
// 编译报错:'ra': 必须初始化引用
//int& ra;
int& b = a;
int c = 20;
// 这里并非让 b 引用 c,因为 C++ 引用不能改变指向,
// 这里是一个赋值
b = c;
cout << &a << endl;
cout << &b << endl;
cout << &c << endl;
return 0;
}
void Swap(int& rx, int& ry) {
int tmp = rx;
rx = ry;
ry = tmp;
}
int main() {
int x = 0, y = 1;
cout << x << " " << y << endl;
Swap(x, y);
cout << x << " " << y << endl;
return 0;
}
#include<iostream>
using namespace std;
typedef int STDataType;
typedef struct Stack {
STDataType* a;
int top;
int capacity;
}ST;
void STInit(ST& rs, int n = 4) {
rs.a = (STDataType*)malloc(n * sizeof(STDataType));
rs.top = 0;
rs.capacity = n;
}
// 栈顶
void STPush(ST& rs, STDataType x) {
assert(rs);
// 满了,扩容
if (rs.top == rs.capacity) {
printf("扩容\n");
int newcapacity = rs.capacity == 0 ? 4 : rs.capacity * 2;
STDataType* tmp = (STDataType*)realloc(rs.a, newcapacity * sizeof(STDataType));
if (tmp == NULL) {
perror("realloc fail");
return;
}
rs.a = tmp;
rs.capacity = newcapacity;
}
rs.a[rs.top] = x;
rs.top++;
}
// int STTop(ST& rs)
int& STTop(ST& rs) {
assert(rs.top > 0);
return rs.a[rs.top];
}
int main() {
// 调用全局的
ST st1;
STInit(st1);
STPush(st1, 1);
STPush(st1, 2);
cout << STTop(st1) << endl;
STTop(st1) += 10;
cout << STTop(st1) << endl;
return 0;
}
#include<iostream>
using namespace std;
typedef struct SeqList {
int a[10];
int size;
}SLT;
// 一些主要用 C 代码实现版本数据结构教材中,使用 C++ 引用替代指针传参,目的是简化程序,避开复杂的指针,但是很多同学没学过引用,导致一头雾水。
void SeqPushBack(SLT& sl, int x) {}
typedef struct ListNode {
int val;
struct ListNode* next;
}LTNode, *PNode;
// 指针变量也可以取别名,这里 LTNode*& phead 就是给指针变量取别名
// 这样就不需要用二级指针了,相对而言简化了程序
//void ListPushBack(LTNode** phead, int x)
//void ListPushBack(LTNode*& phead, int x)
void ListPushBack(PNode& phead, int x) {
PNode newnode = (PNode)malloc(sizeof(LTNode));
newnode->val = x;
newnode->next = NULL;
if (phead == NULL) {
phead = newnode;
} else {
//...
}
}
int main() {
PNode plist = NULL;
ListPushBack(plist, 1);
return 0;
}
int main() {
const int a = 10;
// 编译报错:error C2440: '初始化': 无法从'const int'转换为'int &'
// 这里的引用是对 a 访问权限的放大
//int& ra = a;
// 这样才可以
const int& ra = a;
// 编译报错:error C3892: 'ra': 不能给常量赋值
//ra++;
// 这里的引用是对 b 访问权限的缩小
int b = 20;
const int& rb = b;
// 编译报错:error C3892: 'rb': 不能给常量赋值
//rb++;
return 0;
}
#include<iostream>
using namespace std;
int main() {
int a = 10;
const int& ra = 30;
// 编译报错: '初始化': 无法从'int'转换为'int &'
// int& rb = a * 3;
const int& rb = a*3;
double d = 12.34;
// 编译报错:'初始化': 无法从'double'转换为'int &'
// int& rd = d;
const int& rd = d;
return 0;
}
C++ 中指针和引用就像两个性格迥异的亲兄弟,指针是哥哥,引用是弟弟,在实践中他们相辅相成,功能有重叠性,但是各有自己的特点,互相不可替代。
#include<iostream>
using namespace std;
inline int Add(int x, int y) {
int ret = x + y;
ret += 1;
ret += 1;
ret += 1;
return ret;
}
int main() {
// 可以通过汇编观察程序是否展开
// 有 call Add 语句就是没有展开,没有就是展开了
int ret = Add(1, 2);
cout << Add(1, 2) * 5 << endl;
return 0;
}
#include<iostream>
using namespace std;
// 实现一个 ADD 宏函数的常见问题
//#define ADD(int a, int b) return a + b;
//#define ADD(a, b) a + b;
//#define ADD(a, b) (a + b)
// 正确的宏实现
#define ADD(a, b) ((a) + (b))
// 为什么不能加分号?
// 为什么要加外面的括号?
// 为什么要加里面的括号?
int main() {
int ret = ADD(1, 2);
cout << ADD(1, 2) << endl;
cout << ADD(1, 2)*5 << endl;
int x = 1, y = 2;
ADD(x & y, x | y); // -> (x&y+x|y)
return 0;
}
// F.h
#include <iostream>
using namespace std;
inline void f(int i);
// F.cpp
#include "F.h"
void f(int i) {
cout << i << endl;
}
// main.cpp
#include "F.h"
int main() {
// 链接错误:无法解析的外部符号 "void __cdecl f(int)" (?f@@YAXH@Z)
f(10);
return 0;
}
NULL 实际上是一个宏,在传统的 C 头文件 (stddef.h) 中,可以看到如下代码:
#ifndef NULL
#ifdef __cplusplus
#define NULL 0
#else
#define NULL ((void *)0)
#endif
#endif
#include<iostream>
using namespace std;
void f(int x) {
cout << "f(int x)" << endl;
}
void f(int* ptr) {
cout << "f(int* ptr)" << endl;
}
int main() {
f(0); // 本想通过 f(NULL) 调用指针版本的 f(int*) 函数,但是由于 NULL 被定义成 0,调用了 f(int x),因此与程序的初衷相悖。
f(NULL);
f((int*)NULL);
// 编译报错:error C2665: 'f': 2 个重载中没有一个是能转换所有参数类型
// f((void*)NULL);
f(nullptr);
return 0;
}