当前位置: 首页 > news >正文

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;  // 自动调用析构函数
}
http://www.xdnf.cn/news/95005.html

相关文章:

  • 状态模式(State Pattern)详解
  • Hooks的使用限制及原因
  • 单例模式:确保唯一实例的设计模式
  • mall-cook 本地运行
  • 基于MTF的1D-2D-CNN-LSTM-Attention时序图像多模态融合的故障识别,适合研究学习(Matlab完整源码和数据),附模型研究报告
  • VUE Element-ui Message 消息提示组件自定义封装
  • Android Cordova 开发 - Cordova 解读初始化项目(index.html meta、Cordova.js、config.xml)
  • 【PCB工艺】运放电路中的负反馈机制
  • 2025.04.23华为机考第三题-300分
  • 零基础入门 Verilog VHDL:在线仿真与 FPGA 实战全流程指南
  • 力扣-第645题《错误的集合》
  • 咖啡机语音芯片方案-WTN6040FP-14S直接驱动4欧/3W喇叭-大功率输出
  • 每日一练(4~23):特别数的和
  • label studio的安装
  • docker底层原理简述
  • 解析虚拟机与Docker容器化服务的本质差异及Docker核心价值
  • 大语言模型(LLM)的Prompt Engineering:从入门到精通
  • Godot学习-3D基本环境设置以及3D角色移动
  • 力扣DAY63-67 | 热100 | 二分:搜索插入位置、搜索二维矩阵、排序数组查找元素、搜索旋转排序数组、搜索最小值
  • 如何预约VMware VCP线下考试?
  • 【Java后端】MyBatis 与 MyBatis-Plus 如何防止 SQL 注入?从原理到实战
  • Kotlin 协程在 LiveData 中的完美封装:CoroutineLiveData 全解
  • Spring Boot 项目:如何在 JAR 运行时读取外部配置文件
  • Ubuntu启动SMB(Samba)服务步骤
  • RocketMQ面试题:进阶部分
  • [LLaVA] Visual Instruction Tuning
  • MFC案例:使用键盘按键放大、缩小窗口图像的实验
  • 【Unity笔记】Unity 编辑器扩展:一键查找场景中组件引用关系(含完整源码)(组件引用查找工具实现笔记)
  • Kafka
  • Vmware安装centos7和Redis