C++是由丹麦计算机科学家Bjarne Stroustrup于1979年在贝尔实验室开发的一种静态类型、编译式、通用型编程语言。最初被称为"C with Classes"(带类的C),1983年更名为C++。它既具有高级语言的抽象特性,又保留了底层硬件操作能力,被广泛应用于系统软件、应用软件、驱动程序、嵌入式软件、高性能服务器和客户端应用以及娱乐软件等开发领域。
作为C语言的超集,C++引入了面向对象编程(OOP)特性,包括:
这使得C++成为游戏开发(如Unreal引擎)、系统编程(如操作系统开发)和高性能计算(如金融交易系统)等领域的首选语言。根据TIOBE编程语言排行榜,C++长期保持在前5名最受欢迎的编程语言之列。
Windows平台:
Linux平台:
macOS平台:
专业级IDE:
轻量级IDE:
文本编辑器+插件:
// 预处理指令,引入标准输入输出库
#include
// 使用标准命名空间,避免每次都要写std::
using namespace std;
// 程序入口函数,返回值为int类型
int main() {
// cout是标准输出流对象
// << 是流插入运算符
// "Hello, World!"是字符串常量
// endl是换行并刷新缓冲区
cout << "Hello, World!" << endl;
// 返回0表示程序正常结束
return 0;
}
编译运行步骤:
g++ hello.cpp -o hello
./hello
(Linux/macOS)或hello.exe
(Windows)类型 | 说明 | 大小(字节) | 取值范围 | 示例 |
---|---|---|---|---|
int | 整型 | 4 | -2^31 ~ 2^31-1 | int age = 25; |
float | 单精度浮点 | 4 | ±1.18×10^-38 ~ ±3.4×10^38 | float pi = 3.14f; |
double | 双精度浮点 | 8 | ±2.23×10^-308 ~ ±1.79×10^308 | double pi = 3.1415; |
char | 字符 | 1 | -128 ~ 127 | char c = 'A'; |
bool | 布尔值 | 1 | true/false | bool flag = true; |
void | 无类型 | - | - | void func(); |
wchar_t | 宽字符 | 2/4 | 0 ~ 65535 | wchar_t wc = L'中'; |
short | 短整型 | 2 | -32768 ~ 32767 | short s = 100; |
long | 长整型 | 4/8 | 平台相关 | long l = 100000L; |
long long | 长长整型 | 8 | -2^63 ~ 2^63-1 | long long ll = 1LL; |
unsigned | 无符号修饰 | - | 0 ~ 2^n-1 | unsigned int ui; |
// 基本if语句
if (score >= 60) {
cout << "及格" << endl;
}
// if-else语句
if (score >= 90) {
cout << "优秀" << endl;
} else if (score >= 80) {
cout << "良好" << endl;
} else if (score >= 70) {
cout << "中等" << endl;
} else if (score >= 60) {
cout << "及格" << endl;
} else {
cout << "不及格" << endl;
}
// 三目运算符(条件运算符)
string result = (score >= 60) ? "及格" : "不及格";
// switch语句
switch (grade) {
case 'A':
cout << "优秀";
break;
case 'B':
cout << "良好";
break;
case 'C':
cout << "及格";
break;
default:
cout << "不及格";
}
// 传统for循环
for (int i = 0; i < 10; i++) {
cout << i << " ";
}
// 范围for循环(C++11)
vector vec = {1, 2, 3, 4, 5};
for (auto num : vec) {
cout << num << " ";
}
// while循环
int i = 0;
while (i < 10) {
cout << i << " ";
i++;
}
// do-while循环
int j = 0;
do {
cout << j << " ";
j++;
} while (j < 10);
// 循环控制语句
for (int k = 0; k < 10; k++) {
if (k == 5) break; // 跳出循环
if (k % 2 == 0) continue; // 跳过本次循环
cout << k << " ";
}
// 函数声明(原型)
double calculateCircleArea(double radius);
// 函数实现
double calculateCircleArea(double radius) {
const double PI = 3.1415926;
return PI * radius * radius;
}
// 函数调用
double area = calculateCircleArea(5.0);
cout << "圆的面积: " << area << endl;
// 默认参数
void printMessage(string msg = "Hello") {
cout << msg << endl;
}
// 函数重载
void print(int num) {
cout << "整数: " << num << endl;
}
void print(double num) {
cout << "浮点数: " << num << endl;
}
void print(string str) {
cout << "字符串: " << str << endl;
}
// 1. 值传递(创建副本)
void incrementByValue(int num) {
num++; // 不影响原始变量
}
// 2. 引用传递(操作原始变量)
void incrementByReference(int &num) {
num++; // 修改原始变量
}
// 3. 指针传递(通过地址访问)
void incrementByPointer(int *num) {
(*num)++; // 解引用后修改
}
// 使用示例
int main() {
int a = 10;
incrementByValue(a);
cout << a; // 输出10
incrementByReference(a);
cout << a; // 输出11
incrementByPointer(&a);
cout << a; // 输出12
return 0;
}
// 银行账户类示例
class BankAccount {
private: // 私有成员,外部不可直接访问
string accountNumber;
string accountHolder;
double balance;
public: // 公有接口
// 构造函数
BankAccount(string num, string holder, double bal)
: accountNumber(num), accountHolder(holder), balance(bal) {}
// 存款方法
void deposit(double amount) {
if (amount > 0) {
balance += amount;
cout << "存款成功,当前余额: " << balance << endl;
} else {
cout << "存款金额必须大于0" << endl;
}
}
// 取款方法
bool withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
cout << "取款成功,当前余额: " << balance << endl;
return true;
} else {
cout << "取款失败,余额不足或金额无效" << endl;
return false;
}
}
// 查询余额
double getBalance() const {
return balance;
}
// 显示账户信息
void display() const {
cout << "账户: " << accountNumber
<< ", 持有人: " << accountHolder
<< ", 余额: " << balance << endl;
}
};
// 使用示例
int main() {
BankAccount account("123456789", "张三", 1000.0);
account.deposit(500);
account.withdraw(200);
account.display();
return 0;
}
1. 封装(Encapsulation)
2. 继承(Inheritance)
// 基类
class Shape {
protected:
int width, height;
public:
void setDimensions(int w, int h) {
width = w;
height = h;
}
};
// 派生类
class Rectangle : public Shape {
public:
int area() {
return width * height;
}
};
// 使用
Rectangle rect;
rect.setDimensions(5, 3);
cout << rect.area(); // 输出15
3. 多态(Polymorphism)
class Animal {
public:
virtual void makeSound() {
cout << "动物发出声音" << endl;
}
};
class Dog : public Animal {
public:
void makeSound() override {
cout << "汪汪汪" << endl;
}
};
class Cat : public Animal {
public:
void makeSound() override {
cout << "喵喵喵" << endl;
}
};
// 使用多态
void animalSound(Animal* animal) {
animal->makeSound();
}
int main() {
Animal* animal1 = new Dog();
Animal* animal2 = new Cat();
animalSound(animal1); // 汪汪汪
animalSound(animal2); // 喵喵喵
delete animal1;
delete animal2;
return 0;
}
// 基本指针操作
int var = 42;
int* ptr = &var; // ptr存储var的地址
cout << "变量值: " << var << endl; // 42
cout << "指针值: " << ptr << endl; // 0x7ffee3a5a8dc(地址)
cout << "指针指向的值: " << *ptr << endl; // 42
// 指针运算
int arr[] = {10, 20, 30};
int* arrPtr = arr; // 指向数组第一个元素
cout << *arrPtr << endl; // 10
cout << *(arrPtr + 1) << endl; // 20 (指针移动4字节)
// const与指针
int x = 10, y = 20;
const int* ptr1 = &x; // 指针指向常量
ptr1 = &y; // 可以改变指向
// *ptr1 = 30; // 错误:不能修改指向的值
int* const ptr2 = &x; // 常量指针
*ptr2 = 30; // 可以修改指向的值
// ptr2 = &y; // 错误:不能改变指向
// 单个对象动态分配
int* numPtr = new int(42);
cout << *numPtr << endl; // 42
delete numPtr;
// 数组动态分配
int size = 5;
int* arr = new int[size]{1, 2, 3, 4, 5};
for (int i = 0; i < size; i++) {
cout << arr[i] << " "; // 1 2 3 4 5
}
cout << endl;
delete[] arr; // 释放数组内存
// 智能指针(C++11)
#include
unique_ptr uPtr(new int(100));
cout << *uPtr << endl; // 100
// 不需要手动delete,离开作用域自动释放
shared_ptr sPtr1 = make_shared(200);
shared_ptr sPtr2 = sPtr1; // 共享所有权
cout << *sPtr1 << " " << *sPtr2 << endl; // 200 200
容器 | 描述 | 特点 | 适用场景 |
---|---|---|---|
vector | 动态数组 | 随机访问快,尾部操作高效 | 需要频繁随机访问 |
list | 双向链表 | 插入删除高效,不支持随机访问 | 频繁在中间插入删除 |
deque | 双端队列 | 头尾操作高效 | 需要两端操作 |
array | 固定大小数组 | 栈上分配,大小固定 | 需要固定大小容器 |
forward_list | 单向链表 | 更节省空间 | 只需要单向遍历 |
map | 键值对集合(红黑树实现) | 自动排序,查找高效 | 需要键值对且有序 |
unordered_map | 哈希表实现的键值对 | 查找最快,无序 | 需要快速查找不关心顺序 |
set | 唯一元素集合(红黑树) | 自动排序 | 需要唯一元素集合且有序 |
unordered_set | 哈希表实现的唯一元素集合 | 查找最快,无序 | 需要快速查找唯一元素 |
stack | 栈 | LIFO(后进先出) | 需要栈结构 |
queue | 队列 | FIFO(先进先出) | 需要队列结构 |
priority_queue | 优先队列 | 元素按优先级排序 | 需要优先级处理 |
#include
#include
#include
using namespace std;
int main() {
vector numbers = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3};
// 排序
sort(numbers.begin(), numbers.end());
// 1 1 2 3 3 4 5 5 6 9
// 反转
reverse(numbers.begin(), numbers.end());
// 9 6 5 5 4 3 3 2 1 1
// 查找
auto it = find(numbers.begin(), numbers.end(), 5);
if (it != numbers.end()) {
cout << "找到5,位置: " << distance(numbers.begin(), it) << endl;
}
// 去重(需要先排序)
sort(numbers.begin(), numbers.end());
auto last = unique(numbers.begin(), numbers.end());
numbers.erase(last, numbers.end());
// 1 2 3 4 5 6 9
// 遍历并打印
for_each(numbers.begin(), numbers.end(), [](int n) {
cout << n << " ";
});
cout << endl;
// 统计
int countFives = count(numbers.begin(), numbers.end(), 5);
cout << "5出现次数: " << countFives << endl;
// 最大值/最小值
auto minIt = min_element(numbers.begin(), numbers.end());
auto maxIt = max_element(numbers.begin(), numbers.end());
cout << "最小值: " << *minIt << ", 最大值: " << *maxIt << endl;
return 0;
}
入门书籍:
进阶书籍:
高级主题:
参考网站:
社区论坛:
在线课程:
循序渐进学习路径
实践项目建议
调试技巧
编码规范
持续学习
通过系统学习和不断实践,你将能够掌握C++这一强大而灵活的编程语言,开发出高效可靠的软件系统。