C++ 语言

精选 C++ 语言 常用指令与核心速查备忘单,涵盖高频用法、配置参数与实用技巧。

#入门指南

#hello.cpp 示例 示例

#include <iostream>

int main() {
    std::cout << "Hello CheatSheets\n";
    return 0;
}

编译并运行

$ g++ hello.cpp -o hello
$ ./hello
Hello CheatSheets

#变量声明 (Variables)

int number = 5;       // Integer
float f = 0.95;       // Floating number
double PI = 3.14159;  // Floating number
char yes = 'Y';       // Character
std::string s = "ME"; // String (text)
bool isRight = true;  // Boolean

// Constants
const float RATE = 0.8;

int age {25};         // Since C++11
std::cout << age;     // Print 25

#基础数据类型 (Primitive Data Types)

Data Type Size Range
int 4 bytes -231 to 231-1
float 4 bytes N/A
double 8 bytes N/A
char 1 byte -128 to 127
bool 1 byte true / false
void N/A N/A
wchar_t 2 or 4 bytes 1 wide character

#用户输入 (User Input)

int num;

std::cout << "Type a number: ";
std::cin >> num;

std::cout << "You entered " << num;

#交换变量 (Swap)

int a = 5, b = 10;
std::swap(a, b);

// Outputs: a=10, b=5
std::cout << "a=" << a << ", b=" << b;

#代码注释 (Comments)

// A single one line comment in C++

/* This is a multiple line comment
   in C++ */

#条件判断 (If statement)

if (a == 10) {
    // do something
}

参阅: Conditionals

#Loops

for (int i = 0; i < 10; i++) {
    std::cout << i << "\n";
}

参阅: Loops

#Functions

#include <iostream>

void hello(); // Declaring

int main() {  // main function
    hello();    // Calling
}

void hello() { // Defining
    std::cout << "Hello CheatSheets!\n";
}

参阅: Functions

#References

int i = 1;
int& ri = i; // ri is a reference to i

ri = 2; // i is now changed to 2
std::cout << "i=" << i;

i = 3;   // i is now changed to 3
std::cout << "ri=" << ri;

ri and i refer to the same memory location.

#Namespaces

#include <iostream>
namespace ns1 {int val(){return 5;}}
int main()
{
    std::cout << ns1::val();
}

#include <iostream>
namespace ns1 {int val(){return 5;}}
using namespace ns1;
using namespace std;
int main()
{
    cout << val();
}

Namespaces allow global identifiers under a name

#C++ Arrays

#Declaration

std::array<int, 3> marks; // Definition
marks[0] = 92;
marks[1] = 97;
marks[2] = 98;

// Define and initialize
std::array<int, 3> = {92, 97, 98};

// With empty members
std::array<int, 3> marks = {92, 97};
std::cout << marks[2]; // Outputs: 0

#Manipulation

┌─────┬─────┬─────┬─────┬─────┬─────┐
| 92  | 97  | 98  | 99  | 98  | 94  |
└─────┴─────┴─────┴─────┴─────┴─────┘
   0     1     2     3     4     5

std::array<int, 6> marks = {92, 97, 98, 99, 98, 94};

// Print first element
std::cout << marks[0];

// Change 2nd element to 99
marks[1] = 99;

// Take input from the user
std::cin >> marks[2];

#Displaying

char ref[5] = {'R', 'e', 'f'};

// Range based for loop
for (const int &n : ref) {
    std::cout << std::string(1, n);
}

// Traditional for loop
for (int i = 0; i < sizeof(ref); ++i) {
    std::cout << ref[i];
}

#Multidimensional

     j0   j1   j2   j3   j4   j5
   ┌────┬────┬────┬────┬────┬────┐
i0 | 1  | 2  | 3  | 4  | 5  | 6  |
   ├────┼────┼────┼────┼────┼────┤
i1 | 6  | 5  | 4  | 3  | 2  | 1  |
   └────┴────┴────┴────┴────┴────┘

int x[2][6] = {
    {1,2,3,4,5,6}, {6,5,4,3,2,1}
};
for (int i = 0; i < 2; ++i) {
    for (int j = 0; j < 6; ++j) {
        std::cout << x[i][j] << " ";
    }
}
// Outputs: 1 2 3 4 5 6 6 5 4 3 2 1

#C++ Conditionals

#If Clause

if (a == 10) {
    // do something
}

int number = 16;

if (number % 2 == 0)
{
    std::cout << "even";
}
else
{
    std::cout << "odd";
}

// Outputs: even

#Else if Statement

int score = 99;
if (score == 100) {
    std::cout << "Superb";
}
else if (score >= 90) {
    std::cout << "Excellent";
}
else if (score >= 80) {
    std::cout << "Very Good";
}
else if (score >= 70) {
    std::cout << "Good";
}
else if (score >= 60)
    std::cout << "OK";
else
    std::cout << "What?";

#Operators

#Relational Operators

a == b a is equal to b
a != b a is NOT equal to b
a < b a is less than b
a > b a is greater b
a <= b a is less than or equal to b
a >= b a is greater or equal to b

#Assignment Operators

Example Equivalent to
a += b Aka a = a + b
a -= b Aka a = a - b
a *= b Aka a = a * b
a /= b Aka a = a / b
a %= b Aka a = a % b

#Logical Operators

Example Meaning
exp1 && exp2 Both are true (AND)
exp1 || exp2 Either is true (或)
!exp exp is false (NOT)

#Bitwise Operators

Operator Description
a & b Binary AND
a | b Binary 或
a ^ b Binary X或
~ a Binary One's Complement
a << b Binary Shift Left
a >> b Binary Shift Right

#Ternary Operator

           ┌── True ──┐
Result = Condition ? Exp1 : Exp2;
           └───── False ─────┘

int x = 3, y = 5, max;
max = (x > y) ? x : y;

// Outputs: 5
std::cout << max << std::endl;

int x = 3, y = 5, max;
if (x > y) {
    max = x;
} else {
    max = y;
}
// Outputs: 5
std::cout << max << std::endl;
int age {25};         // C++11 统一列表初始化
std::cout << age;     // 输出 25

#基础数据类型 (Primitive Data Types)

数据类型 字节大小 取值范围
int 4 字节 -231 231-1
float 4 字节 不适用
double 8 字节 不适用
char 1 字节 -128 127
bool 1 字节 true / false
void 不适用 不适用
wchar_t 2 4 字节 1 个宽字符

#用户控制台输入 (User Input)

int num;

std::cout << "Type a number: ";
std::cin >> num;

std::cout << "You entered " << num;

#变量互换 (Swap)

int a = 5, b = 10;
std::swap(a, b);

// 输出: a=10, b=5
std::cout << "a=" << a << ", b=" << b;

#代码注释

// C++ 单行注释语法

/* C++
   多行注释语法 */

#If 条件判断语句

if (a == 10) {
    // 条件成立执行对应代码
}

参阅: 流程控制详解

#循环语句 (Loops)

for (int i = 0; i < 10; i++) {
    std::cout << i << "\n";
}

参阅: 循环详解

#函数 (Functions)

#include <iostream>

void hello(); // 函数前置声明

int main() {  // 入口 main 函数
    hello();    // 函数调用
}

void hello() { // 函数定义
    std::cout << "Hello CheatSheets!\n";
}

参阅: 函数详解

#引用 (References)

int i = 1;
int& ri = i; // ri 是 i 的引用别名

ri = 2; // i 的值随之改变为 2
std::cout << "i=" << i;

i = 3;   // i 的值随之改变为 3
std::cout << "ri=" << ri;

rii 物理上指向相同的内存空间。

#命名空间 (Namespaces)

#include <iostream>
namespace ns1 {int val(){return 5;}}
int main()
{
    std::cout << ns1::val();
}

#include <iostream>
namespace ns1 {int val(){return 5;}}
using namespace ns1;
using namespace std;
int main()
{
    cout << val();
}

命名空间充当容器,防止在大型工程中发生全局标识符命名冲突。

#C++ 数组 (Arrays)

#声明与初始化 (Declaration)

std::array<int, 3> marks; // 声明容器
marks[0] = 92;
marks[1] = 97;
marks[2] = 98;

// 声明并直接初始化
std::array<int, 3> = {92, 97, 98};

// 带有空缺元素的列表初始化
std::array<int, 3> marks = {92, 97};
std::cout << marks[2]; // 默认补零,输出: 0

#元素操作 (Manipulation)

┌─────┬─────┬─────┬─────┬─────┬─────┐
| 92  | 97  | 98  | 99  | 98  | 94  |
└─────┴─────┴─────┴─────┴─────┴─────┘
   0     1     2     3     4     5

std::array<int, 6> marks = {92, 97, 98, 99, 98, 94};

// 打印首元素
std::cout << marks[0];

// 将第 2 个元素修改为 99
marks[1] = 99;

// 从控制台接收输入赋值给第 3 个元素
std::cin >> marks[2];

#遍历显示 (Displaying)

char ref[5] = {'R', 'e', 'f'};

// 基于范围的 for 循环 (Range-based)
for (const int &n : ref) {
    std::cout << std::string(1, n);
}

// 传统索引 for 循环
for (int i = 0; i < sizeof(ref); ++i) {
    std::cout << ref[i];
}

#多维数组 (Multidimensional)

     j0   j1   j2   j3   j4   j5
   ┌────┬────┬────┬────┬────┬────┐
i0 | 1  | 2  | 3  | 4  | 5  | 6  |
   ├────┼────┼────┼────┼────┼────┤
i1 | 6  | 5  | 4  | 3  | 2  | 1  |
   └────┴────┴────┴────┴────┴────┘

int x[2][6] = {
    {1,2,3,4,5,6}, {6,5,4,3,2,1}
};
for (int i = 0; i < 2; ++i) {
    for (int j = 0; j < 6; ++j) {
        std::cout << x[i][j] << " ";
    }
}
// 输出: 1 2 3 4 5 6 6 5 4 3 2 1

#C++ 流程控制 (Conditionals)

#If 条件判断

if (a == 10) {
    // 执行代码
}

int number = 16;

if (number % 2 == 0)
{
    std::cout << "even";
}
else
{
    std::cout << "odd";
}

// 输出: even

#Else if 多分支判断

int score = 99;
if (score == 100) {
    std::cout << "Superb";
}
else if (score >= 90) {
    std::cout << "Excellent";
}
else if (score >= 80) {
    std::cout << "Very Good";
}
else if (score >= 70) {
    std::cout << "Good";
}
else if (score >= 60)
    std::cout << "OK";
else
    std::cout << "What?";

#运算符大全 (Operators)

关系运算符

表达式 含义说明
a == b a 等于 b
a != b a 不等于 b
a < b a 小于 b
a > b a 大于 b
a <= b a 小于等于 b
a >= b a 大于等于 b

赋值运算符

简写语法 完整等价表达式
a += b a = a + b
a -= b a = a - b
a *= b a = a * b
a /= b a = a / b
a %= b a = a % b

逻辑运算符

语法示例 含义说明
exp1 && exp2 两者均为真 (逻辑与)
exp1 || exp2 任意为真 (逻辑或)
!exp 条件取反 (逻辑非)

位运算符

运算符 功能说明
a & b 按位与 (Binary AND)
a | b 按位或
a ^ b 按位异或 (Binary XOR)
~ a 按位取反
a << b 二进制左移
a >> b 二进制右移

#三元运算符 (Ternary Operator)

           ┌── 条件为真 ──┐
结果 = 条件表达式 ? 表达式1 : 表达式2;
           └───── 条件为假 ─────┘

int x = 3, y = 5, max;
max = (x > y) ? x : y;

// 输出: 5
std::cout << max << std::endl;

int x = 3, y = 5, max;
if (x > y) {
    max = x;
} else {
    max = y;
}
// 输出: 5
std::cout << max << std::endl;

#Switch 条件选择语句

int num = 2;
switch (num) {
    case 0:
        std::cout << "Zero";
        break;
    case 1:
        std::cout << "One";
        break;
    case 2:
        std::cout << "Two";
        break;
    case 3:
        std::cout << "Three";
        break;
    default:
        std::cout << "What?";
        break;
}

#C++ 循环结构 (Loops)

#While 循环

int i = 0;
while (i < 6) {
    std::cout << i++;
}

// 输出: 012345

#Do-while 循环

int i = 1;
do {
    std::cout << i++;
} while (i <= 5);

// 输出: 12345

#Continue 语句 (跳过本次循环)

for (int i = 0; i < 10; i++) {
    if (i % 2 == 0) {
        continue;
    }
    std::cout << i;
} // 输出: 13579

#无限循环 (Dead Loop)

while (true) { // true 或 1
    std::cout << "infinite loop";
}

for (;;) {
    std::cout << "infinite loop";
}

for(int i = 1; i > 0; i++) {
    std::cout << "infinite loop";
}

#for_each 高阶遍历 (C++11 起)

#include <iostream>
#include <array>
#include <algorithm>

int main()
{
    auto print = [](int num) { std::cout << num << std::endl; };

    std::array<int, 4> arr = {1, 2, 3, 4};
    std::for_each(arr.begin(), arr.end(), print);
    return 0;
}

#基于范围的 for 循环 (Range-based, C++11 起)

for (int n : {1, 2, 3, 4, 5}) {
    std::cout << n << " ";
}
// 输出: 1 2 3 4 5

std::string hello = "qr.warpnav.com";
for (char c: hello)
{
    std::cout << c << " ";
}
// 输出: q r . w a r p n a v . c o m

#Break 语句 (终止退出循环)

int password, times = 0;
while (password != 1234) {
    if (times++ >= 3) {
        std::cout << "Locked!\n";
        break;
    }
    std::cout << "Password: ";
    std::cin >> password; // 输入
}

#For 循环多变量变体

for (int i = 0, j = 2; i < 3; i++, j--){
    std::cout << "i=" << i << ",";
    std::cout << "j=" << j << ";";
}
// 输出: i=0,j=2;i=1,j=1;i=2,j=0;

#C++ 函数 (Functions)

#参数与返回值

#include <iostream>

int add(int a, int b) {
    return a + b;
}

int main() {
    std::cout << add(10, 20);
}

add 函数接收两个 int 类型参数并返回一个 int 结果。

#函数重载 (Overloading)

void fun(string a, string b) {
    std::cout << a + " " + b;
}
void fun(string a) {
    std::cout << a;
}
void fun(int a) {
    std::cout << a;
}

#内置标准库函数

#include <iostream>
#include <cmath> // 引入 cmath 库

int main() {
    // sqrt() 函数来自 cmath 库
    std::cout << sqrt(9);
}

#C++ 类与面向对象

#定义类 (Class)

class MyClass {
  public:             // 访问控制修饰符
    int myNum;        // 属性 (整型)
    string myString;  // 属性 (字符串)
};

#创建对象 (Object)

MyClass myObj;  // 创建 MyClass 的对象实例

myObj.myNum = 15;          // 为属性赋值 15
myObj.myString = "Hello";  // 为属性赋值 "Hello"

cout << myObj.myNum << endl;         // 输出 15
cout << myObj.myString << endl;      // 输出 "Hello"

#构造函数 (Constructors)

class MyClass {
  public:
    int myNum;
    string myString;
    MyClass() {  // 构造函数
      myNum = 0;
      myString = "";
    }
};

MyClass myObj;  // 创建对象

cout << myObj.myNum << endl;         // 输出 0
cout << myObj.myString << endl;      // 输出 ""

#析构函数 (Destructors)

class MyClass {
  public:
    int myNum;
    string myString;
    MyClass() {  // 构造函数
      myNum = 0;
      myString = "";
    }
    ~MyClass() {  // 析构函数
      cout << "对象已被销毁。" << endl;
    }
};

MyClass myObj;  // 创建对象

// 商业逻辑代码...

// 当对象超出生命周期作用域时,析构函数将被自动触发执行

#类成员方法 (Class Methods)

class MyClass {
  public:
    int myNum;
    string myString;
    void myMethod() {  // 类内部成员方法
      cout << "Hello World!" << endl;
    }
};

MyClass myObj;  // 创建对象
myObj.myMethod();  // 调用成员方法

#访问修饰符 (Access Modifiers)

class MyClass {
  public:     // 公有成员
    int x;    // 外部均可访问
  private:    // 私有成员
    int y;    // 仅本类内部可访问
  protected:  // 受保护成员
    int z;    // 本类与子类可访问
};

MyClass myObj;
myObj.x = 25;  // 允许 (public)
myObj.y = 50;  // 禁止 (private)
myObj.z = 75;  // 禁止 (protected)

#Getter 与 Setter 封装

class MyClass {
  private:
    int myNum;
  public:
    void setMyNum(int num) {  // Setter 写方法
      myNum = num;
    }
    int getMyNum() {  // Getter 读方法
      return myNum;
    }
};

MyClass myObj;
myObj.setMyNum(15);  // 设置值
cout << myObj.getMyNum() << endl;  // 输出 15

#类继承 (Inheritance)

class Vehicle {
  public:
    string brand = "Ford";
    void honk() {
      cout << "Tuut, tuut!" << endl;
    }
};

class Car : public Vehicle {
  public:
    string model = "Mustang";
};

Car myCar;
myCar.honk();  // 输出 "Tuut, tuut!"
cout << myCar.brand + " " + myCar.model << endl;  // 输出 "Ford Mustang"

#C++ 预处理器 (Preprocessor)

#头文件包含 (Includes)

#include "iostream"
#include <iostream>

#宏定义 (Defines)

#define FOO
#define FOO "hello"

#undef FOO

#条件编译 If

#ifdef DEBUG
  console.log('hi');
#elif defined VERBOSE
  ...
#else
  ...
#endif

#错误捕获 (Error)

#if VERSION == 2.0
  #error Unsupported
  #warning Not really supported
#endif

#带参宏 (Macro)

#define DEG(x) ((x) * 57.29)

#标记拼接 (Token concat)

#define DST(name) name##_s name##_t
DST(object);   #=> object_s object_t;

#字符串化 (Stringification)

#define STR(name) #name
char * a = STR(object);   #=> char * a = "object";

#文件名与行号宏 (FILE & LINE)

#define LOG(msg) console.log(__FILE__, __LINE__, msg)
#=> console.log("file.txt", 3, "hey")

#🔗 参考资源