继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

C++编程入门:从基础到实践

www说
关注TA
已关注
手记 456
粉丝 83
获赞 493
概述

C++ 是一种通用的、面向对象的编程语言,由 Bjarne Stroustrup 于1983年在贝尔实验室开发。它继承自 C 语言,并在保持C语言兼容性的前提下,加入了面向对象编程(OOP)的特性。C++ 是一种编译型语言,广泛应用于底层系统开发、嵌入式系统、游戏开发、服务器端应用和高性能计算任务中。

C++编程基础介绍

1.1 C++语言概述

#include <iostream>

int main() {
    std::cout << "欢迎学习C++编程!这是一个强大的、面向对象的编程语言,由Bjarne Stroustrup开发于1983年。C++继承了C语言的特性,并增加了面向对象编程的元素,广泛应用于底层系统开发、嵌入式系统、游戏开发、服务器端应用和高性能计算领域。";
    return 0;
}

1.2 C++的开发环境搭建

#include <iostream>

int main() {
    std::cout << "为了开始学习C++,您需要安装一个合适的开发环境。推荐使用Visual Studio Code或IntelliJ IDEA作为集成开发环境。完成环境安装后,您还需要配置环境变量,确保在命令行中可以使用g++编译器。";
    return 0;
}

1.3 基本语法学习

1.3.1 变量和数据类型

#include <iostream>

int main() {
    int a = 10; // 定义并初始化整型变量
    double b = 3.14; // 定义并初始化双精度浮点型变量
    std::cout << "整型变量a的值: " << a << std::endl;
    std::cout << "双精度浮点型变量b的值: " << b << std::endl;
    return 0;
}

1.3.2 控制结构(选择、循环、跳转)

#include <iostream>

int main() {
    int x = 5;

    // 选择结构
    if (x > 0) {
        std::cout << "x是正数" << std::endl;
    } else if (x < 0) {
        std::cout << "x是负数" << std::endl;
    } else {
        std::cout << "x是零" << std::endl;
    }

    // 循环结构
    for (int i = 0; i < 5; i++) {
        std::cout << "循环次数: " << i << std::endl;
    }

    // 跳转结构
    for (int i = 0; i < 10; i++) {
        if (i == 5) {
            std::cout << "跳过循环次数: " << i << std::endl;
            continue;
        }
        std::cout << "循环次数: " << i << std::endl;
    }
    return 0;
}

1.3.3 函数与模块化编程

#include <iostream>

void greet() {
    std::cout << "Hello, World!" << std::endl;
}

int main() {
    greet(); // 调用函数
    return 0;
}
C++面向对象编程基础

2.1 类与对象

#include <iostream>

class Person {
public:
    std::string name;
    int age;

    Person(std::string n, int a) : name(n), age(a) {} // 构造函数
    void display() const {
        std::cout << "姓名: " << name << ", 年龄: " << age << std::endl;
    }
};

int main() {
    Person p1("Alice", 25);
    p1.display();
    return 0;
}

2.2 构造函数与析构函数

#include <iostream>

class Account {
public:
    Account(int balance) : balance_(balance) {} // 构造函数
    int getBalance() const { return balance_; }

private:
    int balance_; // 账户余额
};

int main() {
    Account a1(1000);
    std::cout << "账户余额: " << a1.getBalance() << std::endl;
    return 0;
}

2.3 封装、继承与多态

封装

class Animal {
public:
    virtual void makeSound() const {
        std::cout << "动物发出声音" << std::endl;
    }
};

class Dog : public Animal {
public:
    void makeSound() const override {
        std::cout << "狗叫" << std::endl;
    }
};

int main() {
    Animal a;
    a.makeSound(); // 输出 "动物发出声音"

    Dog d;
    d.makeSound(); // 输出 "狗叫"
    return 0;
}

继承

class Bird {
public:
    virtual void fly() const = 0;
};

class Eagle : public Bird {
public:
    void fly() const override {
        std::cout << "老鹰飞行" << std::endl;
    }
};

int main() {
    Bird* bird = new Eagle();
    bird->fly(); // 输出 "老鹰飞行"
    delete bird;
    return 0;
}

多态

class Animal {
public:
    virtual void makeSound() const {
        std::cout << "动物发出声音" << std::endl;
    }
};

class Dog : public Animal {
public:
    void makeSound() const override {
        std::cout << "狗叫" << std::endl;
    }
};

int main() {
    Animal* a1 = new Dog();
    a1->makeSound(); // 输出 "狗叫"
    delete a1;
    return 0;
}
C++常见数据结构与算法实践

3.1 数组、向量与链表

数组

int main() {
    int arr[5] = {1, 2, 3, 4, 5};
    for (int i = 0; i < 5; i++) {
        std::cout << arr[i] << " ";
    }
    std::cout << std::endl;
    return 0;
}

向量

int main() {
    std::vector<int> vec = {1, 2, 3};
    for (int i = 0; i < vec.size(); i++) {
        std::cout << vec[i] << " ";
    }
    std::cout << std::endl;
    vec.push_back(4);
    vec.push_back(5);
    for (int i = 0; i < vec.size(); i++) {
        std::cout << vec[i] << " ";
    }
    std::cout << std::endl;
    return 0;
}

链表

struct ListNode {
    int val;
    ListNode* next;
    ListNode(int x) : val(x), next(nullptr) {}
};

ListNode* createList(int a[], int size) {
    ListNode* head = new ListNode(a[0]);
    ListNode* tail = head;
    for (int i = 1; i < size; i++) {
        ListNode* newNode = new ListNode(a[i]);
        tail->next = newNode;
        tail = newNode;
    }
    return head;
}

int main() {
    int a[] = {1, 2, 3, 4, 5};
    ListNode* list = createList(a, 5);
    while (list != nullptr) {
        std::cout << list->val << " ";
        list = list->next;
    }
    std::cout << std::endl;
    return 0;
}

3.2 栈、队列与哈希表

int main() {
    std::stack<int> s;
    s.push(1);
    s.push(2);
    s.push(3);
    std::cout << "栈顶元素: " << s.top() << std::endl;
    s.pop(); // 移除栈顶元素
    std::cout << "栈顶元素: " << s.top() << std::endl;
    return 0;
}

队列

int main() {
    std::queue<int> q;
    q.push(1);
    q.push(2);
    q.push(3);
    std::cout << "队首元素: " << q.front() << std::endl;
    q.pop(); // 移除队首元素
    std::cout << "队首元素: " << q.front() << std::endl;
    return 0;
}

哈希表

int main() {
    std::map<std::string, int> m;
    m["apple"] = 1;
    m["banana"] = 2;
    m["orange"] = 3;
    std::cout << "apple的值: " << m["apple"] << std::endl;
    return 0;
}

3.3 排序算法(冒泡、快速、归并等)

冒泡排序

int main() {
    int arr[] = {64, 34, 25, 12, 22, 11, 90};
    bubbleSort(arr, 7);
    for (int i = 0; i < 7; i++) {
        std::cout << arr[i] << " ";
    }
    std::cout << std::endl;
    return 0;
}

void bubbleSort(int arr[], int n) {
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                std::swap(arr[j], arr[j + 1]);
            }
        }
    }
}

快速排序

int main() {
    int arr[] = {64, 34, 25, 12, 22, 11, 90};
    quickSort(arr, 0, 6);
    for (int i = 0; i < 7; i++) {
        std::cout << arr[i] << " ";
    }
    std::cout << std::endl;
    return 0;
}

int partition(int arr[], int low, int high) {
    int pivot = arr[high];
    int i = low - 1;
    for (int j = low; j < high; j++) {
        if (arr[j] < pivot) {
            i++;
            std::swap(arr[i], arr[j]);
        }
    }
    std::swap(arr[i + 1], arr[high]);
    return i + 1;
}

void quickSort(int arr[], int low, int high) {
    if (low < high) {
        int pi = partition(arr, low, high);
        quickSort(arr, low, pi - 1);
        quickSort(arr, pi + 1, high);
    }
}

归并排序

int main() {
    int arr[] = {64, 34, 25, 12, 22, 11, 90};
    mergeSort(arr, 0, 6);
    for (int i = 0; i < 7; i++) {
        std::cout << arr[i] << " ";
    }
    std::cout << std::endl;
    return 0;
}

void merge(int arr[], int l, int m, int r) {
    int n1 = m - l + 1;
    int n2 = r - m;
    int L[n1], R[n2];
    for (int i = 0; i < n1; i++) {
        L[i] = arr[l + i];
    }
    for (int j = 0; j < n2; j++) {
        R[j] = arr[m + 1 + j];
    }
    int i, j, k;
    i = 0;
    j = 0;
    k = l;
    while (i < n1 && j < n2) {
        if (L[i] <= R[j]) {
            arr[k] = L[i];
            i++;
        } else {
            arr[k] = R[j];
            j++;
        }
        k++;
    }
    while (i < n1) {
        arr[k] = L[i];
        i++;
        k++;
    }
    while (j < n2) {
        arr[k] = R[j];
        j++;
        k++;
    }
}

void mergeSort(int arr[], int l, int r) {
    if (l < r) {
        int m = l + (r - l) / 2;
        mergeSort(arr, l, m);
        mergeSort(arr, m + 1, r);
        merge(arr, l, m, r);
    }
}

3.4 查找算法(二分、哈希查找)

二分查找

int main() {
    int arr[] = {2, 3, 4, 10, 40};
    int n = sizeof(arr) / sizeof(arr[0]);
    int x = 10;
    int result = binarySearch(arr, 0, n - 1, x);
    if (result == -1) {
        std::cout << "元素不在数组中" << std::endl;
    } else {
        std::cout << "元素在数组中的位置: " << result << std::endl;
    }
    return 0;
}

int binarySearch(int arr[], int l, int r, int x) {
    if (r >= l) {
        int mid = l + (r - l) / 2;
        if (arr[mid] == x) {
            return mid;
        }
        if (arr[mid] > x) {
            return binarySearch(arr, l, mid - 1, x);
        }
        return binarySearch(arr, mid + 1, r, x);
    }
    return -1;
}

哈希查找

int main() {
    std::unordered_map<int, std::string> m;
    m[1] = "apple";
    m[2] = "banana";
    m[3] = "orange";
    int key = 2;
    if (m.find(key) != m.end()) {
        std::cout << "找到键2对应的值: " << m[key] << std::endl;
    } else {
        std::cout << "未找到键2对应的值" << std::endl;
    }
    return 0;
}
C++文件操作与输入输出

4.1 文件读写基本操作

#include <fstream>

int main() {
    std::ofstream file("example.txt", std::ios::out);
    if (file.is_open()) {
        file << "Hello, World!" << std::endl;
        file << "这是从C++程序写入的文本。" << std::endl;
        file.close();
    } else {
        std::cerr << "无法打开文件!" << std::endl;
    }
    std::ifstream fileRead("example.txt");
    if (fileRead.is_open()) {
        std::string line;
        while (std::getline(fileRead, line)) {
            std::cout << line << std::endl;
        }
        fileRead.close();
    } else {
        std::cerr << "无法打开文件!" << std::endl;
    }
    return 0;
}

4.2 使用标准输入输出流

int main() {
    int a, b;
    std::cout << "请输入两个整数: ";
    std::cin >> a >> b;
    std::cout << "a + b = " << a + b << std::endl;
    return 0;
}

4.3 格式化输入输出

int main() {
    std::cout << std::setprecision(2) << std::fixed;
    std::cout << "数值: " << 3.14159 << std::endl; // 输出为 "数值: 3.14"
    return 0;
}
C++异常处理与错误管理

5.1 异常的概念与作用

int main() {
    try {
        int a = 10;
        int b = 0;
        int result = a / b; // 除以零错误
    } catch (std::exception& e) {
        std::cerr << "捕获异常: " << e.what() << std::endl;
    }
    return 0;
}

5.2 使用try-catch块处理异常

int main() {
    try {
        int a, b;
        std::cin >> a >> b;
        if (b == 0) {
            throw std::runtime_error("除数不能为零");
        }
        std::cout << "结果: " << a / b << std::endl;
    } catch (std::exception& e) {
        std::cerr << "捕获异常: " << e.what() << std::endl;
    }
    return 0;
}

5.3 自定义异常类

#include <iostream>

class MyException : public std::exception {
public:
    const char* what() const throw() {
        return "自定义错误:哈希表已满";
    }
};

void handleFullHash() {
    std::unordered_map<std::string, int> m;
    // 当哈希表已满时触发错误
    throw MyException();
}

int main() {
    try {
        handleFullHash();
    } catch (MyException& e) {
        std::cerr << "处理自定义错误: " << e.what() << std::endl;
    }
    return 0;
}
实践项目与案例分析

6.1 小型项目实践

计算器项目

#include <iostream>

double add(double a, double b) {
    return a + b;
}

double subtract(double a, double b) {
    return a - b;
}

double multiply(double a, double b) {
    return a * b;
}

double divide(double a, double b) {
    if (b == 0) {
        throw std::runtime_error("除数不能为零");
    }
    return a / b;
}

int main() {
    double a, b;
    std::cout << "请输入两个数字: ";
    std::cin >> a >> b;
    std::cout << "a + b = " << add(a, b) << std::endl;
    std::cout << "a - b = " << subtract(a, b) << std::endl;
    std::cout << "a * b = " << multiply(a, b) << std::endl;
    try {
        std::cout << "a / b = " << divide(a, b) << std::endl;
    } catch (std::exception& e) {
        std::cerr << "错误: " << e.what() << std::endl;
    }
    return 0;
}

分析经典案例

排序算法应用

#include <iostream>

void bubbleSort(int arr[], int n) {
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                std::swap(arr[j], arr[j + 1]);
            }
        }
    }
}

void quickSort(int arr[], int low, int high) {
    if (low < high) {
        int pi = partition(arr, low, high);
        quickSort(arr, low, pi - 1);
        quickSort(arr, pi + 1, high);
    }
}

int partition(int arr[], int low, int high) {
    int pivot = arr[high];
    int i = low - 1;
    for (int j = low; j < high; j++) {
        if (arr[j] < pivot) {
            i++;
            std::swap(arr[i], arr[j]);
        }
    }
    std::swap(arr[i + 1], arr[high]);
    return i + 1;
}

void merge(int arr[], int l, int m, int r) {
    int n1 = m - l + 1;
    int n2 = r - m;
    int L[n1], R[n2];
    for (int i = 0; i < n1; i++) {
        L[i] = arr[l + i];
    }
    for (int j = 0; j < n2; j++) {
        R[j] = arr[m + 1 + j];
    }
    int i, j, k;
    i = 0;
    j = 0;
    k = l;
    while (i < n1 && j < n2) {
        if (L[i] <= R[j]) {
            arr[k] = L[i];
            i++;
        } else {
            arr[k] = R[j];
            j++;
        }
        k++;
    }
    while (i < n1) {
        arr[k] = L[i];
        i++;
        k++;
    }
    while (j < n2) {
        arr[k] = R[j];
        j++;
        k++;
    }
}

int main() {
    int arr[] = {64, 34, 25, 12, 22, 11, 90};
    int n = sizeof(arr) / sizeof(arr[0]);
    bubbleSort(arr, n);
    quickSort(arr, 0, n - 1);
    mergeSort(arr, 0, n - 1);
    for (int i = 0; i < n; i++) {
        std::cout << arr[i] << " ";
    }
    std::cout << std::endl;
    return 0;
}

讨论项目优化与改进方法

优化排序算法的选择

#include <iostream>

void optimizedBubbleSort(int arr[], int n) {
    bool swapped;
    for (int i = 0; i < n - 1; i++) {
        swapped = false;
        for (int j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                std::swap(arr[j], arr[j + 1]);
                swapped = true;
            }
        }
        if (!swapped) {
            break;
        }
    }
}

int main() {
    int arr[] = {64, 34, 25, 12, 22, 11, 90};
    int n = sizeof(arr) / sizeof(arr[0]);
    optimizedBubbleSort(arr, n);
    for (int i = 0; i < n; i++) {
        std::cout << arr[i] << " ";
    }
    std::cout << std::endl;
    return 0;
}

通过这些实践和案例分析,读者将能够深入理解C++编程的核心概念和实际应用,从而在实际项目中更有效地使用C++语言。

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP