深蓝学院-C++基础与深度解析2023.01期
来百度APP畅享高清图片
C++ 基础与深度解析
C++ 是一种静态类型的、编译式的、通用的、大小写敏感的、不规则的编程语言,支持过程化编程、面向对象编程和泛型编程。C++ 语言的设计目标是提供一种高效且灵活的编程工具,适用于各种应用领域,从操作系统和嵌入式系统到大型应用程序和游戏开发。
本文将详细介绍 C++ 的基础知识,并深入解析一些高级特性,帮助读者全面掌握 C++ 编程。
1. C++ 基础
1.1 基本语法
- Hello World 程序:
- cpp深色版本#include int main() { std::cout << "Hello, World!" << std::endl; return 0;}
- 注释:
-
- 单行注释:// 这是一个单行注释
- 多行注释:/* 这是一个多行注释 */
- 变量声明:
- cpp深色版本int a = 10; // 整型变量double b = 3.14; // 浮点型变量char c = 'A'; // 字符型变量bool d = true; // 布尔型变量
- 常量:
- cpp深色版本const int MAX_SIZE = 100; // 常量
- 基本输入输出:
- cpp深色版本#include int main() { int num; std::cout << "请输入一个数字: "; std::cin >> num; std::cout << "你输入的数字是: " << num << std::endl; return 0;}
1.2 控制结构
- 条件语句:
- cpp深色版本if (a > 0) { std::cout << "a 是正数" << std::endl;} else if (a < 0) { std::cout << "a 是负数" << std::endl;} else { std::cout << "a 是零" << std::endl;}
- 循环语句:
- cpp深色版本// for 循环for (int i = 0; i < 10; ++i) { std::cout << i << " ";}// while 循环int i = 0;while (i < 10) { std::cout << i << " "; ++i;}// do-while 循环int j = 0;do { std::cout << j << " "; ++j;} while (j < 10);
- 跳转语句:
- cpp深色版本break; // 退出循环continue; // 跳过当前循环的剩余部分goto label; // 跳转到指定标签
1.3 函数
- 函数定义:
- cpp深色版本int add(int a, int b) { return a + b;}
- 函数调用:
- cpp深色版本int result = add(5, 3);std::cout << "5 + 3 = " << result << std::endl;
- 默认参数:
- cpp深色版本void printMessage(std::string message, std::string prefix = "Info: ") { std::cout << prefix << message << std::endl;}
- 函数重载:
- cpp深色版本void print(int num) { std::cout << "整数: " << num << std::endl;}void print(double num) { std::cout << "浮点数: " << num << std::endl;}
1.4 数组和指针
- 数组:
- cpp深色版本int arr[5] = {1, 2, 3, 4, 5};std::cout << "数组元素: ";for (int i = 0; i < 5; ++i) { std::cout << arr[i] << " ";}
- 指针:
- cpp深色版本int value = 10;int* ptr = &value;std::cout << "指针指向的值: " << *ptr << std::endl;
- 动态内存分配:
- cpp深色版本int* dynamicArray = new int[5];for (int i = 0; i < 5; ++i) { dynamicArray[i] = i * 10;}for (int i = 0; i < 5; ++i) { std::cout << dynamicArray[i] << " ";}delete[] dynamicArray;
2. 面向对象编程
2.1 类和对象
- 类定义:
- cpp深色版本class Point {private: int x, y;public: Point(int x = 0, int y = 0) : x(x), y(y) {} void setX(int x) { this->x = x; } void setY(int y) { this->y = y; } int getX() const { return x; } int getY() const { return y; } void display() const { std::cout << "Point(" << x << ", " << y << ")" << std::endl; }};
- 对象创建:
- cpp深色版本Point p1(1, 2);p1.display();
2.2 继承
- 基类和派生类:
- cpp深色版本class Shape {public: virtual void draw() const = 0; // 纯虚函数};class Circle : public Shape {private: int radius;public: Circle(int radius) : radius(radius) {} void draw() const override { std::cout << "Drawing a circle with radius " << radius << std::endl; }};class Square : public Shape {private: int side;public: Square(int side) : side(side) {} void draw() const override { std::cout << "Drawing a square with side " << side << std::endl; }};
- 多态:
- cpp深色版本void drawShape(const Shape& shape) { shape.draw();}int main() { Circle c(5); Square s(10); drawShape(c); drawShape(s); return 0;}
2.3 封装
- 访问控制:
- cpp深色版本class BankAccount {private: double balance;public: BankAccount(double initialBalance) : balance(initialBalance) {} void deposit(double amount) { balance += amount; } void withdraw(double amount) { if (amount <= balance) { balance -= amount; } else { std::cout << "Insufficient funds" << std::endl; } } double getBalance() const { return balance; }};
2.4 抽象类和接口
- 抽象类:
- cpp深色版本class Animal {public: virtual ~Animal() = default; virtual void makeSound() const = 0; // 纯虚函数};class Dog : public Animal {public: void makeSound() const override { std::cout << "Woof!" << std::endl; }};class Cat : public Animal {public: void makeSound() const override { std::cout << "Meow!" << std::endl; }};
- 接口:
- cpp深色版本class IRunnable {public: virtual ~IRunnable() = default; virtual void run() const = 0;};class RunnableClass : public IRunnable {public: void run() const override { std::cout << "Running..." << std::endl; }};
3. 泛型编程
3.1 模板
- 函数模板:
- cpp深色版本template T max(T a, T b) { return (a > b) ? a : b;}int main() { int m = max(5, 3); double n = max(3.14, 2.71); std::cout << "Max of 5 and 3 is: " << m << std::endl; std::cout << "Max of 3.14 and 2.71 is: " << n << std::endl; return 0;}
- 类模板:
- cpp深色版本template class Stack {private: std::vector elements;public: void push(T const& element) { elements.push_back(element); } void pop() { if (elements.empty()) { throw std::out_of_range("Stack<>::pop(): empty stack"); } elements.pop_back(); } T top() const { if (elements.empty()) { throw std::out_of_range("Stack<>::top(): empty stack"); } return elements.back(); } bool empty() const { return elements.empty(); }};int main() { Stack intStack; intStack.push(1); intStack.push(2); std::cout << "Top element: " << intStack.top() << std::endl; intStack.pop(); std::cout << "Top element after pop: " << intStack.top() << std::endl; return 0;}
4. 高级特性
4.1 异常处理
- 抛出异常:
- cpp深色版本void divide(int a, int b) { if (b == 0) { throw std::invalid_argument("Division by zero"); } std::cout << "Result: " << a / b << std::endl;}int main() { try { divide(10, 0); } catch (const std::invalid_argument& e) { std::cerr << "Error: " << e.what() << std::endl; } return 0;}
4.2 智能指针
- 智能指针:
- cpp深色版本#include void useSmartPointer() { std::unique_ptr uniquePtr(new int(10)); std::shared_ptr sharedPtr(new int(20)); std::cout << "Unique pointer value: " << *uniquePtr << std::endl; std::cout << "Shared pointer value: " << *sharedPtr << std::endl;}int main() { useSmartPointer(); return 0;}
4.3 Lambda 表达式
- Lambda 表达式:
- cpp深色版本#include #include int main() { std::vector numbers = {1, 2, 3, 4, 5}; // 使用 lambda 表达式进行排序 std::sort(numbers.begin(), numbers.end(), [](int a, int b) { return a > b; }); for (int num : numbers) { std::cout << num << " "; } std::cout << std::endl; return 0;}
4.4 并发编程
- 线程:
- cpp深色版本#include #include void threadFunction() { std::cout << "Thread function running" << std::endl;}int main() { std::thread t(threadFunction); t.join(); std::cout << "Main function completed" << std::endl; return 0;}
- 互斥锁:
- cpp深色版本#include #include std::mutex mtx;void printNumber(int num) { std::lock_guardstd::mutex lock(mtx); std::cout << "Number: " << num << std::endl;}int main() { std::thread t1(printNumber, 1); std::thread t2(printNumber, 2); t1.join(); t2.join(); return 0;}
5. 总结
通过以上内容,你可以全面了解 C++ 的基础知识和高级特性。C++ 是一门强大而灵活的编程语言,适用于各种复杂的应用场景。希望本文对你有所帮助,如果你有任何问题或建议,欢迎留言交流!