C++ 语言全面教程 (基础入门)

我们将从C++的基础开始,逐步深入。C++是一种静态类型、编译式、通用、大小写敏感、支持过程化编程、面向对象编程和泛型编程的编程语言。

首先,我们需要了解一些基本概念,然后通过代码实例来加深理解。

第一部分:基本概念

程序结构:一个C++程序通常包括头文件引用、命名空间、主函数等部分。

数据类型:C++提供了多种数据类型,包括整型、浮点型、字符型、布尔型等。

变量:变量是存储数据的内存位置的名字。

常量:常量是固定值,在程序执行期间不会改变。

运算符:用于执行各种操作,如算术、关系、逻辑等。

控制流:包括条件语句(if, switch)和循环语句(for, while, do-while)等。

函数:函数是一组一起执行一个任务的语句。

数组:数组是存储相同类型数据的集合。

指针:指针是一个变量,其值为另一个变量的地址。

面向对象:类、对象、继承、多态、封装等。

由于内容很多,我们将分步骤进行。首先,我们从最简单的程序开始。

第一个C++程序:Hello World

这个程序将输出"Hello, World!"到控制台。

C++ 语言全面教程

我会从基础概念到实际代码,系统性地教你C++编程。让我们开始这个学习之旅!

第一部分:C++基础概念

1. C++是什么?

C++是一种静态类型编译式多范式的编程语言,支持:

  • 过程化编程
  • 面向对象编程(OOP)
  • 泛型编程
  • 函数式编程

2. 核心特性

  • 高性能:接近硬件,运行速度快
  • 内存管理:支持手动和自动内存管理
  • 标准库:丰富的STL(标准模板库)
  • 兼容C:大部分C代码可在C++中运行

第二部分:从Hello World开始

cpp 复制代码
// 第一个C++程序:Hello World
#include <iostream>  // 引入输入输出流库
using namespace std; // 使用标准命名空间,避免重复写std::

int main() {         // 主函数,程序入口点
    cout << "Hello, World!" << endl;  // 输出文本并换行
    return 0;        // 返回0表示程序正常结束
}

// 输出:
// Hello, World!

第三部分:基本语法详解

1. 变量和数据类型

cpp 复制代码
#include <iostream>
using namespace std;

int main() {
    // 基本数据类型
    int age = 25;                    // 整型,4字节
    float weight = 68.5f;            // 单精度浮点数,4字节
    double price = 99.99;            // 双精度浮点数,8字节
    char grade = 'A';                // 字符型,1字节
    bool isStudent = true;           // 布尔型,true/false
    
    // 输出变量值
    cout << "Age: " << age << endl;
    cout << "Weight: " << weight << " kg" << endl;
    cout << "Price: $" << price << endl;
    cout << "Grade: " << grade << endl;
    cout << "Is student: " << boolalpha << isStudent << endl;
    
    // 类型大小
    cout << "\nSize of int: " << sizeof(int) << " bytes" << endl;
    cout << "Size of double: " << sizeof(double) << " bytes" << endl;
    
    return 0;
}

/*
输出:
Age: 25
Weight: 68.5 kg
Price: $99.99
Grade: A
Is student: true

Size of int: 4 bytes
Size of double: 8 bytes
*/

2. 控制结构

cpp 复制代码
#include <iostream>
using namespace std;

int main() {
    // 1. 条件语句
    int score = 85;
    
    cout << "If-else语句示例:" << endl;
    if (score >= 90) {
        cout << "成绩优秀" << endl;
    } else if (score >= 60) {
        cout << "成绩合格" << endl;
    } else {
        cout << "成绩不合格" << endl;
    }
    
    // 2. switch语句
    cout << "\nSwitch语句示例:" << endl;
    char operation = '*';
    int a = 10, b = 5, result;
    
    switch(operation) {
        case '+':
            result = a + b;
            cout << "加法结果: " << result << endl;
            break;
        case '-':
            result = a - b;
            cout << "减法结果: " << result << endl;
            break;
        case '*':
            result = a * b;
            cout << "乘法结果: " << result << endl;
            break;
        default:
            cout << "未知操作" << endl;
    }
    
    // 3. 循环语句
    cout << "\n循环语句示例:" << endl;
    
    // for循环
    cout << "For循环: ";
    for(int i = 1; i <= 5; i++) {
        cout << i << " ";
    }
    cout << endl;
    
    // while循环
    cout << "While循环: ";
    int j = 1;
    while(j <= 3) {
        cout << j << " ";
        j++;
    }
    cout << endl;
    
    // do-while循环
    cout << "Do-While循环: ";
    int k = 1;
    do {
        cout << k << " ";
        k++;
    } while(k <= 3);
    cout << endl;
    
    return 0;
}

/*
输出:
If-else语句示例:
成绩合格

Switch语句示例:
乘法结果: 50

循环语句示例:
For循环: 1 2 3 4 5 
While循环: 1 2 3 
Do-While循环: 1 2 3 
*/

3. 函数

cpp 复制代码
#include <iostream>
using namespace std;

// 函数声明(原型)
int add(int x, int y);           // 声明函数
void printMessage(string msg);   // 无返回值函数
int factorial(int n);            // 递归函数

int main() {
    // 调用函数
    int sum = add(5, 3);
    cout << "5 + 3 = " << sum << endl;
    
    printMessage("Hello from function!");
    
    // 递归函数调用
    int num = 5;
    cout << num << "! = " << factorial(num) << endl;
    
    return 0;
}

// 函数定义 - 加法函数
int add(int x, int y) {
    return x + y;  // 返回两个数的和
}

// 函数定义 - 打印消息
void printMessage(string msg) {
    cout << "Message: " << msg << endl;
}

// 函数定义 - 计算阶乘(递归)
int factorial(int n) {
    if (n <= 1) {
        return 1;  // 基本情况
    } else {
        return n * factorial(n - 1);  // 递归调用
    }
}

/*
输出:
5 + 3 = 8
Message: Hello from function!
5! = 120
*/

第四部分:面向对象编程(OOP)

1. 类和对象

cpp 复制代码
#include <iostream>
#include <string>
using namespace std;

// 定义一个类
class Student {
private:    // 私有成员,只能在类内部访问
    string name;
    int age;
    float gpa;
    
public:     // 公有成员,可以在外部访问
    // 构造函数 - 创建对象时自动调用
    Student(string n, int a, float g) {
        name = n;
        age = a;
        gpa = g;
        cout << "学生 " << name << " 已创建" << endl;
    }
    
    // 成员函数(方法)
    void displayInfo() {
        cout << "姓名: " << name << endl;
        cout << "年龄: " << age << endl;
        cout << "GPA: " << gpa << endl;
    }
    
    // 设置器(setter)
    void setGPA(float newGPA) {
        if (newGPA >= 0.0 && newGPA <= 4.0) {
            gpa = newGPA;
        }
    }
    
    // 获取器(getter)
    float getGPA() {
        return gpa;
    }
    
    // 析构函数 - 对象销毁时自动调用
    ~Student() {
        cout << "学生 " << name << " 已销毁" << endl;
    }
};

int main() {
    // 创建对象
    Student stu1("张三", 20, 3.5);
    Student stu2("李四", 22, 3.8);
    
    // 调用成员函数
    cout << "\n学生信息:" << endl;
    stu1.displayInfo();
    cout << endl;
    stu2.displayInfo();
    
    // 使用setter和getter
    cout << "\n修改GPA:" << endl;
    stu1.setGPA(3.7);
    cout << "张三的新GPA: " << stu1.getGPA() << endl;
    
    return 0;
}

/*
输出:
学生 张三 已创建
学生 李四 已创建

学生信息:
姓名: 张三
年龄: 20
GPA: 3.5

姓名: 李四
年龄: 22
GPA: 3.8

修改GPA:
张三的新GPA: 3.7
学生 李四 已销毁
学生 张三 已销毁
*/

2. 继承

cpp 复制代码
#include <iostream>
using namespace std;

// 基类
class Shape {
protected:
    float width;
    float height;
    
public:
    Shape(float w, float h) : width(w), height(h) {}
    
    virtual float area() {  // 虚函数,支持多态
        return 0;
    }
    
    void display() {
        cout << "宽度: " << width << ", 高度: " << height << endl;
    }
};

// 派生类 - 矩形
class Rectangle : public Shape {
public:
    Rectangle(float w, float h) : Shape(w, h) {}
    
    float area() override {
        return width * height;
    }
};

// 派生类 - 三角形
class Triangle : public Shape {
public:
    Triangle(float w, float h) : Shape(w, h) {}
    
    float area() override {
        return (width * height) / 2;
    }
};

int main() {
    Rectangle rect(10, 5);
    Triangle tri(10, 5);
    
    cout << "矩形信息:" << endl;
    rect.display();
    cout << "面积: " << rect.area() << endl;
    
    cout << "\n三角形信息:" << endl;
    tri.display();
    cout << "面积: " << tri.area() << endl;
    
    // 多态示例
    cout << "\n多态示例:" << endl;
    Shape* shape1 = &rect;
    Shape* shape2 = &tri;
    
    cout << "矩形面积(通过基类指针): " << shape1->area() << endl;
    cout << "三角形面积(通过基类指针): " << shape2->area() << endl;
    
    return 0;
}

/*
输出:
矩形信息:
宽度: 10, 高度: 5
面积: 50

三角形信息:
宽度: 10, 高度: 5
面积: 25

多态示例:
矩形面积(通过基类指针): 50
三角形面积(通过基类指针): 25
*/

第五部分:标准模板库(STL)

1. 向量(Vector)

cpp 复制代码
#include <iostream>
#include <vector>
#include <algorithm>  // 包含算法函数
using namespace std;

int main() {
    // 创建向量
    vector<int> numbers = {3, 1, 4, 1, 5, 9, 2, 6};
    
    // 访问元素
    cout << "第一个元素: " << numbers[0] << endl;
    cout << "第二个元素: " << numbers.at(1) << endl;
    
    // 遍历向量
    cout << "\n所有元素: ";
    for(int num : numbers) {
        cout << num << " ";
    }
    cout << endl;
    
    // 修改元素
    numbers.push_back(7);  // 添加元素
    numbers.pop_back();    // 删除最后一个元素
    
    // 排序
    sort(numbers.begin(), numbers.end());
    cout << "\n排序后: ";
    for(int num : numbers) {
        cout << num << " ";
    }
    cout << endl;
    
    // 查找元素
    auto it = find(numbers.begin(), numbers.end(), 5);
    if (it != numbers.end()) {
        cout << "找到数字5" << endl;
    }
    
    // 向量大小和容量
    cout << "\n向量大小: " << numbers.size() << endl;
    cout << "向量容量: " << numbers.capacity() << endl;
    
    return 0;
}

/*
输出:
第一个元素: 3
第二个元素: 1

所有元素: 3 1 4 1 5 9 2 6 

排序后: 1 1 2 3 4 5 6 9 
找到数字5

向量大小: 8
向量容量: 16
*/

2. 映射(Map)

cpp 复制代码
#include <iostream>
#include <map>
#include <string>
using namespace std;

int main() {
    // 创建映射(字典)
    map<string, int> ageMap;
    
    // 插入元素
    ageMap["Alice"] = 25;
    ageMap["Bob"] = 30;
    ageMap["Charlie"] = 35;
    
    // 访问元素
    cout << "Alice的年龄: " << ageMap["Alice"] << endl;
    
    // 遍历映射
    cout << "\n所有人员年龄:" << endl;
    for(auto& pair : ageMap) {
        cout << pair.first << ": " << pair.second << "岁" << endl;
    }
    
    // 查找元素
    string name = "Bob";
    auto it = ageMap.find(name);
    if (it != ageMap.end()) {
        cout << "\n找到" << name << ",年龄: " << it->second << endl;
    }
    
    // 检查元素是否存在
    if (ageMap.count("David") == 0) {
        cout << "David不在映射中" << endl;
    }
    
    return 0;
}

/*
输出:
Alice的年龄: 25

所有人员年龄:
Alice: 25岁
Bob: 30岁
Charlie: 35岁

找到Bob,年龄: 30
David不在映射中
*/

第六部分:内存管理和指针

cpp 复制代码
#include <iostream>
using namespace std;

int main() {
    // 1. 栈内存分配
    int stackVar = 10;  // 栈上分配
    
    // 2. 堆内存分配(动态内存)
    int* heapVar = new int(20);  // 在堆上分配内存
    
    cout << "栈变量: " << stackVar << endl;
    cout << "堆变量: " << *heapVar << endl;
    
    // 3. 动态数组
    int* arr = new int[5];  // 动态分配数组
    for(int i = 0; i < 5; i++) {
        arr[i] = i * 10;
    }
    
    cout << "\n动态数组: ";
    for(int i = 0; i < 5; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
    
    // 4. 引用(别名)
    int x = 100;
    int& ref = x;  // ref是x的引用(别名)
    ref = 200;
    
    cout << "\nx的值: " << x << endl;
    cout << "ref的值: " << ref << endl;
    
    // 5. 智能指针(C++11及以上)
    // unique_ptr - 独占所有权
    unique_ptr<int> ptr1(new int(300));
    cout << "\nunique_ptr: " << *ptr1 << endl;
    
    // shared_ptr - 共享所有权
    shared_ptr<int> ptr2 = make_shared<int>(400);
    shared_ptr<int> ptr3 = ptr2;  // 共享所有权
    
    cout << "shared_ptr1: " << *ptr2 << endl;
    cout << "shared_ptr2: " << *ptr3 << endl;
    cout << "引用计数: " << ptr2.use_count() << endl;
    
    // 6. 必须释放动态分配的内存
    delete heapVar;    // 释放单个变量
    delete[] arr;      // 释放数组
    
    return 0;
}

/*
输出:
栈变量: 10
堆变量: 20

动态数组: 0 10 20 30 40 

x的值: 200
ref的值: 200

unique_ptr: 300
shared_ptr1: 400
shared_ptr2: 400
引用计数: 2
*/

第七部分:综合示例 - 简单学生管理系统

cpp 复制代码
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;

class Student {
private:
    string name;
    int id;
    float score;
    
public:
    Student(string n, int i, float s) : name(n), id(i), score(s) {}
    
    string getName() const { return name; }
    int getID() const { return id; }
    float getScore() const { return score; }
    
    void display() const {
        cout << "ID: " << id << ", 姓名: " << name 
             << ", 成绩: " << score << endl;
    }
};

class StudentManager {
private:
    vector<Student> students;
    
public:
    void addStudent(const Student& stu) {
        students.push_back(stu);
        cout << "学生 " << stu.getName() << " 已添加" << endl;
    }
    
    void displayAll() const {
        if (students.empty()) {
            cout << "没有学生记录" << endl;
            return;
        }
        
        cout << "\n所有学生信息:" << endl;
        for(const auto& stu : students) {
            stu.display();
        }
    }
    
    void searchByName(const string& name) const {
        bool found = false;
        cout << "\n查找姓名包含 \"" << name << "\" 的学生:" << endl;
        
        for(const auto& stu : students) {
            if (stu.getName().find(name) != string::npos) {
                stu.display();
                found = true;
            }
        }
        
        if (!found) {
            cout << "未找到相关学生" << endl;
        }
    }
    
    void sortByScore() {
        sort(students.begin(), students.end(), 
             [](const Student& a, const Student& b) {
                 return a.getScore() > b.getScore();  // 降序排序
             });
        cout << "\n按成绩降序排序完成" << endl;
    }
    
    float getAverageScore() const {
        if (students.empty()) return 0.0;
        
        float total = 0;
        for(const auto& stu : students) {
            total += stu.getScore();
        }
        return total / students.size();
    }
};

int main() {
    StudentManager manager;
    
    // 添加学生
    manager.addStudent(Student("张三", 1001, 85.5));
    manager.addStudent(Student("李四", 1002, 92.0));
    manager.addStudent(Student("王五", 1003, 78.5));
    manager.addStudent(Student("张小凡", 1004, 88.0));
    
    // 显示所有学生
    manager.displayAll();
    
    // 查找学生
    manager.searchByName("张");
    
    // 排序
    manager.sortByScore();
    manager.displayAll();
    
    // 计算平均分
    cout << "\n平均成绩: " << manager.getAverageScore() << endl;
    
    return 0;
}

/*
输出:
学生 张三 已添加
学生 李四 已添加
学生 王五 已添加
学生 张小凡 已添加

所有学生信息:
ID: 1001, 姓名: 张三, 成绩: 85.5
ID: 1002, 姓名: 李四, 成绩: 92
ID: 1003, 姓名: 王五, 成绩: 78.5
ID: 1004, 姓名: 张小凡, 成绩: 88

查找姓名包含 "张" 的学生:
ID: 1001, 姓名: 张三, 成绩: 85.5
ID: 1004, 姓名: 张小凡, 成绩: 88

按成绩降序排序完成

所有学生信息:
ID: 1002, 姓名: 李四, 成绩: 92
ID: 1004, 姓名: 张小凡, 成绩: 88
ID: 1001, 姓名: 张三, 成绩: 85.5
ID: 1003, 姓名: 王五, 成绩: 78.5

平均成绩: 86
*/

学习建议和下一步

学习路径建议:

  1. 基础语法 → 2. 函数和数组 → 3. 指针和引用 → 4. 面向对象 → 5. STL → 6. 高级特性

重要主题待学习:

  • 模板和泛型编程
  • 异常处理
  • 文件I/O操作
  • 多线程编程
  • 设计模式
  • 现代C++特性(C++11/14/17/20)

实践建议:

  1. 每天写代码,哪怕只有30分钟
  2. 解决实际问题,如小工具、小游戏
  3. 阅读优秀开源代码
  4. 参与编程挑战(LeetCode等)
相关推荐
侠客行03177 小时前
Mybatis连接池实现及池化模式
java·mybatis·源码阅读
蛇皮划水怪7 小时前
深入浅出LangChain4J
java·langchain·llm
老毛肚8 小时前
MyBatis体系结构与工作原理 上篇
java·mybatis
风流倜傥唐伯虎9 小时前
Spring Boot Jar包生产级启停脚本
java·运维·spring boot
Yvonne爱编码9 小时前
JAVA数据结构 DAY6-栈和队列
java·开发语言·数据结构·python
Re.不晚9 小时前
JAVA进阶之路——无奖问答挑战1
java·开发语言
你这个代码我看不懂9 小时前
@ConditionalOnProperty不直接使用松绑定规则
java·开发语言
fuquxiaoguang9 小时前
深入浅出:使用MDC构建SpringBoot全链路请求追踪系统
java·spring boot·后端·调用链分析
琹箐9 小时前
最大堆和最小堆 实现思路
java·开发语言·算法
__WanG10 小时前
JavaTuples 库分析
java