C++学习笔记

一、基础语法与核心概念

1. 基本语法

  • 变量与数据类型
    int(整数)、float(单精度浮点)、double(双精度浮点)、char(字符)、bool(布尔)。
    示例:

    int age = 25;
    double pi = 3.14159;
    char grade = 'A';
    

  • 运算符与表达式
    算术运算符(+, -, *, /)、关系运算符(==, >, <)、逻辑运算符(&&, ||, !)。
    表达式示例:

    int result = (10 + 5) * 3; // 结果为45
    

  • 控制流

    • if-else
      if (score > 60) {
          cout << "及格";
      } else {
          cout << "不及格";
      }
      

    • 循环语句:
      for循环:
      for (int i = 0; i < 5; i++) {
          cout << i << " ";
      } // 输出:0 1 2 3 4
      

      while循环:
      int count = 0;
      while (count < 3) {
          cout << "Hello! ";
          count++;
      } // 输出:Hello! Hello! Hello!
      

  • 函数
    定义与调用:

    int add(int a, int b) { // 函数定义
        return a + b;
    }
    int sum = add(3, 4);   // 函数调用,sum=7
    

2. 面向对象基础

  • 类与对象

    class Dog {          // 类定义
    private:
        string name;     // 成员变量(封装)
    public:
        Dog(string n) {  // 构造函数
            name = n;
        }
        void bark() {    // 成员函数
            cout << name << "汪汪!";
        }
        ~Dog() {}        // 析构函数
    };
    Dog myDog("Buddy");  // 创建对象
    myDog.bark();        // 调用方法:输出"Buddy汪汪!"
    

  • 继承与多态

    class Animal {       // 基类
    public:
        virtual void sound() { cout << "动物叫"; } // 虚函数(多态基础)
    };
    class Cat : public Animal { // 继承
    public:
        void sound() override { cout << "喵喵!"; } // 重写(多态)
    };
    Animal* a = new Cat();
    a->sound(); // 输出"喵喵!"(多态)
    

3. 指针与引用

  • 指针:存储内存地址,操作符*(解引用)、&(取地址)。
    int num = 10;
    int* ptr = #   // ptr指向num的地址
    cout << *ptr;      // 输出10(解引用)
    

  • 引用:别名,操作符&(声明引用)。
    int a = 5;
    int& ref = a;      // ref是a的引用
    ref = 8;           // 修改ref即修改a
    cout << a;         // 输出8
    

    区别:指针可重赋值、可为nullptr;引用必须初始化且不可变更目标。

4. 数组与字符串

  • 数组
    int arr[3] = {1, 2, 3};
    cout << arr[0]; // 输出1
    

  • 字符串
    C风格:char str[] = "Hello";
    C++ string类:
    #include <string>
    string s = "C++";
    cout << s.length(); // 输出3
    


二、标准库与常用工具

1. STL(标准模板库)

  • 容器

    vector<int> vec = {1, 2, 3}; // 动态数组
    vec.push_back(4);            // 添加元素
    
    map<string, int> scores;     // 键值对容器
    scores["Alice"] = 90;
    

  • 算法

    #include <algorithm>
    sort(vec.begin(), vec.end()); // 排序
    auto it = find(vec.begin(), vec.end(), 2); // 查找元素
    

  • 迭代器:遍历容器

    for (auto it = vec.begin(); it != vec.end(); it++) {
        cout << *it << " ";
    }
    

2. 输入输出流

  • 控制台I/O:
    #include <iostream>
    int x;
    cin >> x;        // 输入
    cout << "x=" << x; // 输出
    

  • 文件流:
    #include <fstream>
    ofstream file("data.txt");
    file << "保存数据"; // 写入文件
    file.close();
    


三、进阶特性

1. 模板(泛型编程)

  • 函数模板
    template <typename T>
    T max(T a, T b) {
        return (a > b) ? a : b;
    }
    cout << max(3, 5); // 输出5
    

  • 类模板(STL基础):
    template <class T>
    class Box {
        T content;
    public:
        void set(T c) { content = c; }
        T get() { return content; }
    };
    Box<int> intBox;
    intBox.set(100);
    

2. 异常处理
try-catch-throw机制:

try {
    if (value < 0) throw "负数错误!";
} catch (const char* msg) {
    cerr << "错误: " << msg;
}

3. 内存管理

  • 动态内存:
    int* p = new int(10); // 分配内存
    delete p;             // 释放内存
    

  • 智能指针(避免泄漏):
    #include <memory>
    unique_ptr<int> uPtr(new int(5)); // 独占所有权
    shared_ptr<int> sPtr = make_shared<int>(10); // 共享所有权
    

4. 其他特性

  • 友元函数:访问私有成员
    class Student {
        int score;
        friend void printScore(Student s); // 友元声明
    };
    void printScore(Student s) {
        cout << s.score; // 可直接访问私有成员
    }
    

  • 运算符重载
    Vector operator+(Vector v) { // 重载+
        return Vector(x + v.x, y + v.y);
    }
    

  • 虚函数与抽象类
    class Shape {
    public:
        virtual double area() = 0; // 纯虚函数(抽象类)
    };
    class Circle : public Shape {
        double area() override { ... } // 必须实现
    };
    

具体语法特性例如(虚函数,构造虚构函数,多态,继承等)后续更新

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐