C++ 快速参考备忘单,提供基本语法和方法。
#include <iostream>
int main() {
std::cout << "你好,备忘单\n"; // "Hello CheatSheets" -> "你好,备忘单"
return 0;
}
编译和运行
$ g++ hello.cpp -o hello
$ ./hello
你好,备忘单
int number = 5; // 整数
float f = 0.95; // 浮点数
double PI = 3.14159; // 浮点数
char yes = 'Y'; // 字符
std::string s = "ME"; // 字符串 (文本)
bool isRight = true; // 布尔值
// 常量
const float RATE = 0.8;
int age {25}; // C++11 起
std::cout << age; // 打印 25
| 数据类型 | 大小 | 范围 |
|---|---|---|
int |
4 字节 | -231 到 231-1 |
float |
4 字节 | N/A |
double |
8 字节 | N/A |
char |
1 字节 | -128 到 127 |
bool |
1 字节 | true / false |
void |
N/A | N/A |
wchar_t |
2 或 4 字节 | 1 宽字符 |
int num;
std::cout << "输入一个数字: "; // "Type a number: " -> "输入一个数字: "
std::cin >> num;
std::cout << "你输入了 " << num; // "You entered " -> "你输入了 "
int a = 5, b = 10;
std::swap(a, b);
// 输出: a=10, b=5
std::cout << "a=" << a << ", b=" << b;
// C++ 中的单行注释
/* 这是 C++ 中的
多行注释 */
#include <iostream>
void hello(); // 声明
int main() { // main 函数
hello(); // 调用
}
void hello() { // 定义
std::cout << "你好,备忘单!\n"; // "Hello CheatSheets!" -> "你好,备忘单!"
}
参见: 函数
int i = 1;
int& ri = i; // ri 是 i 的引用
ri = 2; // i 现在变为 2
std::cout << "i=" << i;
i = 3; // i 现在变为 3
std::cout << "ri=" << ri;
ri 和 i 指向相同的内存位置。
#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();
}
命名空间允许在名称下使用全局标识符
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
┌─────┬─────┬─────┬─────┬─────┬─────┐
| 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];
// 将第二个元素更改为 99
marks[1] = 99;
// 从用户处获取输入
std::cin >> marks[2];
char ref[5] = {'R', 'e', 'f'};
// 基于范围的 for 循环
for (const int &n : ref) {
std::cout << std::string(1, n);
}
// 传统的 for 循环
for (int i = 0; i < sizeof(ref); ++i) {
std::cout << ref[i];
}
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
if (a == 10) {
// 执行某些操作
}
int number = 16;
if (number % 2 == 0)
{
std::cout << "偶数"; // "even" -> "偶数"
}
else
{
std::cout << "奇数"; // "odd" -> "奇数"
}
// 输出: 偶数
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?" -> "什么?"
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 |
exp 为假 (非) |
| 运算符 | 描述 |
|---|---|
a & b |
按位与 |
a | b |
按位或 |
a ^ b |
按位异或 |
~ a |
按位取反 |
a << b |
按位左移 |
a >> b |
按位右移 |
┌── 真 ──┐
结果 = 条件 ? 表达式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;
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;
}
int i = 0;
while (i < 6) {
std::cout << i++;
}
// 输出: 012345
int i = 1;
do {
std::cout << i++;
} while (i <= 5);
// 输出: 12345
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue;
}
std::cout << i;
} // 输出: 13579
while (true) { // true 或 1
std::cout << "无限循环"; // "infinite loop" -> "无限循环"
}
for (;;) {
std::cout << "无限循环";
}
for(int i = 1; i > 0; i++) {
std::cout << "无限循环";
}
#include <iostream>
#include <array>
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 (int n : {1, 2, 3, 4, 5}) {
std::cout << n << " ";
}
// 输出: 1 2 3 4 5
std::string hello = "r3f.cn";
for (char c: hello)
{
std::cout << c << " ";
}
// 输出: Q u i c k R e f . M E (保持原样,因为这是字符串内容)
int password, times = 0;
while (password != 1234) {
if (times++ >= 3) {
std::cout << "已锁定!\n"; // "Locked!" -> "已锁定!"
break;
}
std::cout << "密码: "; // "Password: " -> "密码: "
std::cin >> password; // 输入
}
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;
#include <iostream>
int add(int a, int b) {
return a + b;
}
int main() {
std::cout << add(10, 20);
}
add 是一个接受 2 个 int 类型参数并返回 int 类型的函数
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> // 导入库
int main() {
// sqrt() 来自 cmath
std::cout << sqrt(9);
}
class MyClass {
public: // 访问修饰符
int myNum; // 属性 (int 变量)
string myString; // 属性 (string 变量)
};
MyClass myObj; // 创建 MyClass 的对象
myObj.myNum = 15; // 将 myNum 的值设置为 15
myObj.myString = "你好"; // 将 myString 的值设置为 "你好" ( "Hello" -> "你好")
cout << myObj.myNum << endl; // 输出 15
cout << myObj.myString << endl; // 输出 "你好"
class MyClass {
public:
int myNum;
string myString;
MyClass() { // 构造函数
myNum = 0;
myString = "";
}
};
MyClass myObj; // 创建 MyClass 的对象
cout << myObj.myNum << endl; // 输出 0
cout << myObj.myString << endl; // 输出 ""
class MyClass {
public:
int myNum;
string myString;
MyClass() { // 构造函数
myNum = 0;
myString = "";
}
~MyClass() { // 析构函数
cout << "对象已销毁。" << endl; // "Object destroyed." -> "对象已销毁。"
}
};
MyClass myObj; // 创建 MyClass 的对象
// 此处代码...
// 当程序退出作用域时,对象会自动销毁
class MyClass {
public:
int myNum;
string myString;
void myMethod() { // 在类内部定义的方法/函数
cout << "世界你好!" << endl; // "Hello World!" -> "世界你好!"
}
};
MyClass myObj; // 创建 MyClass 的对象
myObj.myMethod(); // 调用方法
class MyClass {
public: // 公共访问修饰符
int x; // 公共属性
private: // 私有访问修饰符
int y; // 私有属性
protected: // 受保护访问修饰符
int z; // 受保护属性
};
MyClass myObj;
myObj.x = 25; // 允许 (公共)
myObj.y = 50; // 不允许 (私有)
myObj.z = 75; // 不允许 (受保护)
class MyClass {
private:
int myNum;
public:
void setMyNum(int num) { // Setter
myNum = num;
}
int getMyNum() { // Getter
return myNum;
}
};
MyClass myObj;
myObj.setMyNum(15); // 将 myNum 的值设置为 15
cout << myObj.getMyNum() << endl; // 输出 15
class Vehicle {
public:
string brand = "福特"; // "Ford" -> "福特"
void honk() {
cout << "嘟嘟,嘟嘟!" << endl; // "Tuut, tuut!" -> "嘟嘟,嘟嘟!"
}
};
class Car : public Vehicle {
public:
string model = "野马"; // "Mustang" -> "野马"
};
Car myCar;
myCar.honk(); // 输出 "嘟嘟,嘟嘟!"
cout << myCar.brand + " " + myCar.model << endl; // 输出 "福特 野马"
#include "iostream"
#include <iostream>
#define FOO
#define FOO "你好" // "hello" -> "你好"
#undef FOO
#ifdef DEBUG
console.log('嗨'); // 'hi' -> '嗨'
#elif defined VERBOSE
...
#else
...
#endif
#if VERSION == 2.0
#error 不支持 // "Unsupported" -> "不支持"
#warning 并非真正支持 // "Not really supported" -> "并非真正支持"
#endif
#define DEG(x) ((x) * 57.29)
#define DST(name) name##_s name##_t
DST(object); #=> object_s object_t;
#define STR(name) #name
char * a = STR(object); #=> char * a = "object";
#define LOG(msg) console.log(__FILE__, __LINE__, msg)
#=> console.log("file.txt", 3, "嘿") // "hey" -> "嘿"
| 转义序列 | 字符 |
|---|---|
\b |
退格 |
\f |
换页 |
\n |
换行 |
\r |
回车 |
\t |
水平制表符 |
\v |
垂直制表符 |
\\ |
反斜杠 |
\' |
单引号 |
\" |
双引号 |
\? |
问号 |
\0 |
空字符 |
C++ 信息图表和备忘单 (hackingcpp.com)
C++ 参考 (cppreference.com)
C++ 语言教程 (cplusplus.com)