C++语言速成,语法及示例宝典汇总整理

该文章已生成可运行项目,

一、基础语法

  1. 程序框架
    cpp
#include <iostream>    // 标准输入输出头文件
using namespace std;   // 使用标准命名空间(简化代码)

int main() {
    cout << "Hello World!" << endl;  // 输出语句
    return 0;
}
  1. 输入输出
    cpp
int age;
double salary;
cout << "请输入年龄和工资:";
cin >> age >> salary;  // 输入多个变量

二、数据类型与变量

  1. 基本类型扩展
    类型 说明 示例
    bool 布尔类型(true/false) bool flag = true;
    string 字符串(需包含) string s = “C++”;
    auto 自动类型推断(C++11) auto x = 5.0;
  2. 引用
    cpp
int a = 10;
int &ref = a;   // 引用必须初始化
ref = 20;       // a的值变为20

三、面向对象编程

  1. 类与对象
    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();
  1. 继承与多态
    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(标准模板库)

  1. 容器
    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;
  1. 算法
    cpp
#include <algorithm>
vector<int> nums = {3, 1, 4, 2};
sort(nums.begin(), nums.end());  // 排序
auto it = find(nums.begin(), nums.end(), 4);  // 查找元素
  1. 智能指针(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++特性

  1. 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; };
  1. 范围for循环(C++11)
    cpp
vector<int> nums = {1, 2, 3};
for (auto &num : nums) {
    num *= 2;  // 修改元素值
}
  1. 移动语义(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;
}

七、模板编程

  1. 函数模板
    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
  1. 类模板
    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;  // 自动调用析构函数
}
本文章已经生成可运行项目
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

承接电子控制项目开发

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值