1. 基础语法
1.1 Hello World
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!" << endl;
return 0;
}
1.2 注释
// 单行注释
/*
多行注释
第二行
*/
2. 数据类型
2.1 基本数据类型
int age = 25; // 整数
float price = 19.99f; // 单精度浮点数
double pi = 3.14159; // 双精度浮点数
char grade = 'A'; // 字符
bool isActive = true; // 布尔值
2.2 类型修饰符
short smallNumber; // 短整型
long bigNumber; // 长整型
unsigned int positive; // 无符号整数
3. 变量和常量
3.1 变量声明
int x = 10;
int y(20); // 构造函数初始化
int z{30}; // 统一初始化(C++11)
3.2 常量
const double PI = 3.14159;
constexpr int SIZE = 100; // 编译时常量(C++11)
4. 运算符
4.1 算术运算符
int a = 10, b = 3;
int sum = a + b; // 13
int diff = a - b; // 7
int prod = a * b; // 30
int quot = a / b; // 3
int mod = a % b; // 1
4.2 比较运算符
bool result;
result = (a == b); // 等于
result = (a != b); // 不等于
result = (a > b); // 大于
result = (a < b); // 小于
result = (a >= b); // 大于等于
result = (a <= b); // 小于等于
4.3 逻辑运算符
bool x = true, y = false;
bool andResult = x && y; // AND
bool orResult = x || y; // OR
bool notResult = !x; // NOT
5. 控制流
5.1 条件语句
// if-else
if (score >= 90) {
grade = 'A';
} else if (score >= 80) {
grade = 'B';
} else {
grade = 'C';
}
// switch
switch (day) {
case 1:
cout << "Monday";
break;
case 2:
cout << "Tuesday";
break;
default:
cout << "Other day";
}
5.2 循环
// for 循环
for (int i = 0; i < 10; i++) {
cout << i << " ";
}
// while 循环
int i = 0;
while (i < 10) {
cout << i << " ";
i++;
}
// do-while 循环
int j = 0;
do {
cout << j << " ";
j++;
} while (j < 10);
6. 函数
6.1 函数定义
// 函数声明
int add(int a, int b);
// 函数定义
int add(int a, int b) {
return a + b;
}
// 默认参数
void printMessage(string msg = "Hello") {
cout << msg << endl;
}
6.2 函数重载
int multiply(int a, int b) {
return a * b;
}
double multiply(double a, double b) {
return a * b;
}
7. 数组和字符串
7.1 数组
int numbers[5] = {1, 2, 3, 4, 5};
int matrix[2][3] = {{1,2,3}, {4,5,6}};
// 遍历数组
for (int i = 0; i < 5; i++) {
cout << numbers[i] << " ";
}
7.2 字符串
#include <string>
string str1 = "Hello";
string str2 = "World";
string result = str1 + " " + str2; // 字符串连接
// 字符串操作
int length = str1.length();
bool isEmpty = str1.empty();
string sub = str1.substr(1, 3); // 从位置1开始取3个字符
8. 指针和引用
8.1 指针
int x = 10;
int *ptr = &x; // ptr指向x的地址
cout << *ptr; // 解引用,输出10
// 动态内存分配
int *arr = new int[10];
delete[] arr; // 释放内存
8.2 引用
int x = 10;
int &ref = x; // ref是x的引用
ref = 20; // 现在x也是20
9. 面向对象编程
9.1 类定义
class Rectangle {
private:
double width, height;
public:
// 构造函数
Rectangle(double w, double h) : width(w), height(h) {}
// 成员函数
double area() {
return width * height;
}
// getter 和 setter
double getWidth() { return width; }
void setWidth(double w) { width = w; }
};
// 使用类
Rectangle rect(5.0, 3.0);
cout << "Area: " << rect.area();
9.2 继承
class Shape {
public:
virtual double area() = 0; // 纯虚函数
};
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) : radius(r) {}
double area() override {
return 3.14159 * radius * radius;
}
};
10. 标准模板库(STL)
10.1 Vector
#include <vector>
vector<int> numbers = {1, 2, 3};
numbers.push_back(4); // 添加元素
numbers.pop_back(); // 删除最后一个元素
for (int num : numbers) { // 范围for循环
cout << num << " ";
}
10.2 Map
#include <map>
map<string, int> ages;
ages["Alice"] = 25;
ages["Bob"] = 30;
for (auto &pair : ages) {
cout << pair.first << ": " << pair.second << endl;
}
10.3 Algorithm
#include <algorithm>
#include <vector>
vector<int> numbers = {3, 1, 4, 1, 5, 9};
sort(numbers.begin(), numbers.end()); // 排序
auto it = find(numbers.begin(), numbers.end(), 4); // 查找
if (it != numbers.end()) {
cout << "Found at position: " << it - numbers.begin();
}
11. 异常处理
#include <stdexcept>
try {
int age = -5;
if (age < 0) {
throw invalid_argument("Age cannot be negative");
}
} catch (const invalid_argument& e) {
cout << "Error: " << e.what() << endl;
} catch (...) {
cout << "Unknown error occurred" << endl;
}
12. 文件操作
#include <fstream>
// 写入文件
ofstream outFile("data.txt");
outFile << "Hello, File!" << endl;
outFile.close();
// 读取文件
ifstream inFile("data.txt");
string line;
while (getline(inFile, line)) {
cout << line << endl;
}
inFile.close();
13. 现代C++特性(C++11及以上)
13.1 Auto 关键字
auto x = 10; // x 是 int
auto y = 3.14; // y 是 double
auto z = "hello"; // z 是 const char*
vector<int> numbers = {1, 2, 3};
for (auto num : numbers) { // 自动类型推断
cout << num << " ";
}
13.2 Lambda 表达式
// 简单的lambda
auto square = [](int x) { return x * x; };
cout << square(5); // 输出 25
// 带捕获的lambda
int multiplier = 3;
auto times = [multiplier](int x) { return x * multiplier; };
cout << times(4); // 输出 12
13.3 智能指针
#include <memory>
// 独占所有权
unique_ptr<int> ptr1 = make_unique<int>(10);
// 共享所有权
shared_ptr<int> ptr2 = make_shared<int>(20);
// 弱引用
weak_ptr<int> weakPtr = ptr2;