C&C++快速入门

20、运算符重载

1、课程目标

  • 理解运算符重载的概念
  • 掌握常见运算符的重载方法
  • 理解友元函数
  • 了解运算符重载的限制

2、名词解释

术语 说明
运算符重载 为自定义类型定义运算符行为
operator 重载运算符的关键字
友元函数 可访问私有成员的非成员函数
成员运算符 作为类成员实现
非成员运算符 作为全局/友元函数实现

3、代码实现

1. 基础运算符重载

#include <iostream>
using namespace std;

class Vector2D {
private:
    float x, y;
    
public:
    Vector2D(float x = 0, float y = 0) : x(x), y(y) {}
    
    // + 运算符
    Vector2D operator+(const Vector2D& other) const {
        return Vector2D(x + other.x, y + other.y);
    }
    
    // - 运算符
    Vector2D operator-(const Vector2D& other) const {
        return Vector2D(x - other.x, y - other.y);
    }
    
    // * 标量乘法
    Vector2D operator*(float scalar) const {
        return Vector2D(x * scalar, y * scalar);
    }
    
    // == 比较
    bool operator==(const Vector2D& other) const {
        return x == other.x && y == other.y;
    }
    
    // 输出
    friend ostream& operator<<(ostream& os, const Vector2D& v) {
        return os << "(" << v.x << ", " << v.y << ")";
    }
};

int main() {
    cout << "=== 运算符重载 ===" << endl << endl;
    
    Vector2D v1(3, 4);
    Vector2D v2(1, 2);
    
    cout << "v1 = " << v1 << endl;
    cout << "v2 = " << v2 << endl;
    cout << "v1 + v2 = " << (v1 + v2) << endl;
    cout << "v1 - v2 = " << (v1 - v2) << endl;
    cout << "v1 * 2 = " << (v1 * 2) << endl;
    cout << "v1 == v2: " << (v1 == v2 ? "true" : "false") << endl;
    
    return 0;
}

2. 下标运算符和赋值运算符

#include <iostream>
#include <cstring>
using namespace std;

class ByteArray {
private:
    unsigned char* m_data;
    int m_size;
    
public:
    ByteArray(int size) : m_size(size) {
        m_data = new unsigned char[size];
        memset(m_data, 0, size);
    }
    
    // 拷贝构造
    ByteArray(const ByteArray& other) : m_size(other.m_size) {
        m_data = new unsigned char[m_size];
        memcpy(m_data, other.m_data, m_size);
    }
    
    ~ByteArray() {
        delete[] m_data;
    }
    
    // 赋值运算符
    ByteArray& operator=(const ByteArray& other) {
        if (this != &other) {
            delete[] m_data;
            m_size = other.m_size;
            m_data = new unsigned char[m_size];
            memcpy(m_data, other.m_data, m_size);
        }
        return *this;
    }
    
    // 下标运算符
    unsigned char& operator[](int index) {
        return m_data[index];
    }
    
    const unsigned char& operator[](int index) const {
        return m_data[index];
    }
    
    int Size() const { return m_size; }
};

int main() {
    cout << "=== 下标和赋值 ===" << endl << endl;
    
    ByteArray arr(5);
    arr[0] = 0xDE;
    arr[1] = 0xAD;
    arr[2] = 0xBE;
    arr[3] = 0xEF;
    
    cout << "数据: ";
    for (int i = 0; i < arr.Size(); i++) {
        printf("%02X ", arr[i]);
    }
    cout << endl;
    
    return 0;
}

3、课后作业

3.1、作业1:实现复数类

实现加减乘除运算符。

3.2、作业2:实现智能指针

实现->*运算符的简单智能指针。