C++语言速成,语法及示例宝典汇总整理
一、基础语法
- 程序框架
cpp
#include <iostream> // 标准输入输出头文件
using namespace std; // 使用标准命名空间(简化代码)int main() {cout << "Hello World!" << endl; // 输出语句return 0;
}
- 输入输出
cpp
int age;
double salary;
cout << "请输入年龄和工资:";
cin >> age >> salary; // 输入多个变量
二、数据类型与变量
- 基本类型扩展
类型 说明 示例
bool 布尔类型(true/false) bool flag = true;
string 字符串(需包含) string s = “C++”;
auto 自动类型推断(C++11) auto x = 5.0; - 引用
cpp
int a = 10;
int &ref = a; // 引用必须初始化
ref = 20; // a的值变为20
三、面向对象编程
- 类与对象
cpp
class Student {
private:string name;int age;
public:// 构造函数Student(string n, int a) : name(n), age(a) {}// 成员函数void display() {cout << name << ", " << age << endl;}
};// 使用
Student stu("Alice", 18);
stu.display();
- 继承与多态
cpp
// 基类
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.14 * radius * radius;}
};// 多态示例
Shape *shape = new Circle(5.0);
cout << shape->area() << endl; // 输出78.5
四、STL(标准模板库)
- 容器
cpp
// Vector(动态数组)
#include <vector>
vector<int> vec = {1, 2, 3};
vec.push_back(4); // 添加元素// Map(键值对)
#include <map>
map<string, int> scores;
scores["Alice"] = 90;
scores["Bob"] = 85;
- 算法
cpp
#include <algorithm>
vector<int> nums = {3, 1, 4, 2};
sort(nums.begin(), nums.end()); // 排序
auto it = find(nums.begin(), nums.end(), 4); // 查找元素
- 智能指针(C++11)
cpp
#include <memory>
// unique_ptr(独占所有权)
unique_ptr<int> ptr1 = make_unique<int>(10);// shared_ptr(共享所有权)
shared_ptr<int> ptr2 = make_shared<int>(20);
shared_ptr<int> ptr3 = ptr2; // 引用计数+1
五、现代C++特性
- Lambda表达式(C++11)
cpp
auto sum = [](int a, int b) -> int { return a + b; };
cout << sum(3, 5) << endl; // 输出8// 捕获外部变量
int factor = 2;
auto multiply = [factor](int x) { return x * factor; };
- 范围for循环(C++11)
cpp
vector<int> nums = {1, 2, 3};
for (auto &num : nums) {num *= 2; // 修改元素值
}
- 移动语义(C++11)
cpp
// 右值引用
string s1 = "Hello";
string s2 = move(s1); // s1变为空,资源转移给s2## 六、异常处理cpp
try {int age = -5;if (age < 0) {throw invalid_argument("年龄不能为负数");}
} catch (const exception &e) {cerr << "错误: " << e.what() << endl;
}
七、模板编程
- 函数模板
cpp
template <typename T>
T max(T a, T b) {return (a > b) ? a : b;
}
cout << max(3, 5) << endl; // 输出5
cout << max(2.7, 1.8) << endl; // 输出2.7
- 类模板
cpp
template <class T>
class Box {
private:T content;
public:void set(T t) { content = t; }T get() { return content; }
};Box<int> intBox;
intBox.set(100);
八、文件操作
cpp
#include <fstream>
// 写入文件
ofstream outFile("data.txt");
outFile << "C++ File IO" << endl;
outFile.close();// 读取文件
ifstream inFile("data.txt");
string line;
while (getline(inFile, line)) {cout << line << endl;
}
九、常见问题与优化
内存泄漏
cpp
int *arr = new int[100];
delete[] arr; // 必须释放数组内存
未初始化指针cpp
int *p = nullptr; // 初始化空指针
if (p != nullptr) {*p = 10; // 安全访问
}
性能优化建议
优先使用const引用传递大型对象:
cpp
void print(const vector<int> &vec) { ... }
避免不必要的拷贝(使用移动语义)。
总结
核心特性:
面向对象:封装、继承、多态
资源管理:RAII(资源获取即初始化)、智能指针
泛型编程:模板与STL容器/算法
嵌入式开发注意:
慎用异常和动态内存(部分嵌入式环境不支持)。
使用constexpr(C++11)实现编译期计算优化。
学习路径:
掌握基础后,学习设计模式(如工厂模式、观察者模式)。
结合Qt框架开发GUI,或使用ROS进行机器人编程。
示例代码(智能指针管理资源):
cpp
class Sensor {
public:Sensor() { cout << "传感器初始化" << endl; }~Sensor() { cout << "传感器释放" << endl; }
};int main() {unique_ptr<Sensor> sensor = make_unique<Sensor>();return 0; // 自动调用析构函数
}