这里写自定义目录标题
-
-
- 命名空间 namespace
- 字面量 literals
- 变量 variables
- 运算符 operators
- 枚举类型 enumerated types
- 结构体 structs
- 条件语句 conditional statements
- 条件运算符 conditional operators
- 逻辑运算符 logical evaluation operators
- 三向比较符 three-way comparisons
- 函数 functions
- 属性 attributes
- c数组 c-style arrays
- std::array
- std::vector
- std::pair
- std::optional
- 结构化绑定 structured bindings
- 循环 loops
- 初始化程序列表 initializer lists
- 字符串 strings
- 面向对象 object-oriented language
- 范围解析 Scope Resolution
- 统一初始化 uniform initialization
- 指针和动态内存 Pointers and Dynamic Memory
- 常量 const
- constexpr
- consteval
- 引用 references
- const_cast
- 异常 exceptions
- 类型别名 type aliases
- 类型定义 typedefs
- 类型推断 Type Inference
-
命名空间 namespace
命名空间解决了不同代码段之间的命名冲突问题。将函数定义在命名空间之下,使用时通过::(scope resolution operator)调用,或 using 指令引入。using 可以只引入命名空间下的一个函数。
一个文件可以包含多个 using,但是需要注意过度使用导致互相影响。
不要在 header file 中使用 using,导致全局引入,尽量在小的范围内引入。
namespace mycode {
void foo() {
std::cout << "foo() called in the mycode namespace" << std::endl;
}
}
// 1. scope resolution operator
mycode::foo(); // Calls the "foo" function in the "mycode" namespace
// 2. using directive
using namespace mycode;
foo(); // Implies mycode::foo();
// 3. refer to a particular item within a namespace
using std::cout;
cout << "Hello, World!" << std::endl;
命名空间可以嵌套定义。
namespace MyLibraries {
namespace Networking {
namespace FTP {
/* ... */
}
}
}
// c++ 17 syntax
namespace MyLibraries::Networking::FTP {
/* ... */
}
命名空间可以定义别名
namespace MyFTP = MyLibraries::Networking::FTP;
字面量 literals
标准字面量,用于在代码中写入数字和字母
- Decimal literal, 123
- Octal literal, 0173
- Hexadecimal literal, 0x7B
- Binary literal, 0b1111011
- floating-point value (such as 3.14f)
- double floating-point value (such as 3.14)
- hexadecimal floating-point literal (such as 0x3.ABCp-10 and 0Xb.cp12l)
- single character (such as ‘a’)
- zero-terminated array of characters (such as “character array”)
也支持自定义的字面量类型
变量 variables
代码中的任何地方都可以定义变量,定义后的变量在当前block中都可以使用。定义变量可以不初始化值,这样很容易引入bug,编译器一般会有检查。
int uninitializedInt;
// C++11 uniform initialization syntax(recommended)
int initializedInt {
7 };
cout << format("{} is a random value", uninitializedInt) << endl;
cout << format("{} was assigned an initial value", initializedInt) << endl;
// assignment initialization syntax
int initializedInt = 7;
c++ 是强类型的,变量都需要有类型
- (signed) int / signed
- (signed) short (int)
- (signed) long (int)
- (signed) long long (int)
- unsigned (int)
- unsigned short (int)
- unsigned long (int)
- unsigned long long (int)
- float
- double
- long double
- char
- unsigned char
- signed char
- char8_t (since C++20)
- char16_t (since C++20)
- char32_t (since C++20)
- wchar_t
- bool
string 以类库的形式提供
数字的最大最小值推荐 使用 std::numeric_limits
cout << "int:\n";
cout << format("Max int value: {}\n", numeric_limits<int>::max());
cout << format("Min int value: {}\n", numeric_limits<int>::min());
cout << format("Lowest int value: {}\n", numeric_limits<int>::lowest());
cout << "\ndouble:\n";
cout << format("Max double value: {}\n", numeric_limits<double>::max());
cout << format("Min double value: {}\n", numeric_limits<double>::min());
cout << format("Lowest double value: {}\n", numeric_limits<double>::lowest());
变量可以初始化为对应类型的0值
float myFloat {
};
int myInt {
};
变量可以使用cast转化为另一种类型
float myFloat {
3.14f };
int i1 {
(int)myFloat };
int i2 {
int(myFloat) };
int i3 {
static_cast<int>(myFloat) };
使用浮点数计算会丢失精度
特殊的浮点数
- +/-infinity 无限大/无限小
- NaN 不是一个数字,例如除以0,未定义的结果
运算符 operators
三种类型的运算符
- unary 一个表达式的计算
- binary 两个表达式的计算
- ternary 三个表达式的计算
运算符(优先级从低到高)
++ -- (postfix)
! ++ -- (prefix)
*/ %
+ -
<< >>
&
^
|
= += -= *= /= %= &= |= ^= <<= >>=
例子
int someInteger {
256 }; short someShort;
long someLong;
float someFloat;
double someDouble;
someInteger++;
someInteger *= 2;
someShort = static_cast<short>(someInteger);
someLong = someShort * 10000;
someFloat = someLong + 0.785f;
someDouble = static_cast<double>(someFloat) / 100000;
cout << someDouble << endl;
枚举类型 enumerated types
枚举定义一个变量的取值范围
enum class PieceType {
King,
Queen,
Rook,
Pawn
};
PieceType piece {
PieceType::King };
enum class State {
Unknown, Started, Finished };
enum class Error {
None, BadInput, DiskFull, Unknown};
// c++ 20 using enum declaration
using enum PieceType;
PieceType piece {
King };
// old style
enum PieceType {
PieceTypeKing, PieceTypeQueen, PieceTypeRook, PieceTypePawn };
PieceType myPiece {
PieceTypeQueen };
结构体 structs
使用结构体可以把一个或多个类型封装成一个新类型
c++20支持定义模块,模块接口文件的扩展名通常为.cppm,可以使用 export 关键字导出,以方便外部使用
employee.cppm
export module employee;
export struct Employee {
char firstInitial;
char lastInitial;
int employeeNumber;
int salary;
};
main.cpp
import <iostream>;
import <format>;
import employee;
using namespace std;
int main() {
// Create and populate an employee.
Employee anEmployee;
anEmployee.firstInitial = 'J';
anEmployee.lastInitial = 'D';
anEmployee.employeeNumber = 42;
anEmployee.salary = 80000;
// Output the values of an employee.
cout << format("Employee: {}{}", anEmployee.firstInitial, anEmployee.lastInitial) << endl;
cout << format("Number: {}", anEmployee.employeeNumber) << endl;
cout << format("Salary: ${}", anEmployee.salary) << endl;
}
条件语句 conditional statements
if/else Statements
if (<initializer>; <conditional_expression>) {
<if_body>
} else if (<else_if_expression>) {
<else_if_body>
} else {
<else_body>
}
switch Statements
switch (<initializer>; <expression>) {
<body>
}
enum class Mode {
Default, Custom, Standard };
int value {
42 };
Mode mode {
/* ... */ };
switch (mode) {
using enum Mode;
case Custom:
value = 84;
case Standard:
case Default:
// Do something with value ...
break;
}
条件运算符 conditional operators
三元运算符,简单的实现if
if [something] then [perform action], otherwise [perform some other action].
cout << ((i > 2) ? "yes" : "no");
逻辑运算符 logical evaluation operators
< <= > >=
==
!=
<=>
!
&&
||
三向比较符 three-way comparisons
三向比较运算符可用于确定两个值的顺序。它也被称为太空飞船操作员&#