C++学习系列(7):运算符重载

C++学习系列(7):运算符重载

1. 引言

在 C++ 中,运算符(如 +-*/ 等)默认只适用于基本数据类型(如 intdouble)。
如果希望 自定义类型(如类) 也能使用运算符,我们可以 重载运算符 使其具有特殊功能。

本篇博客,我们将学习:

  • 运算符重载的基本语法
  • 常见的运算符重载(+、-、==、<< 等)
  • 友元函数与成员函数的运算符重载
  • 运算符重载的注意事项

2. 运算符重载的基本语法

运算符重载(Operator Overloading)是 C++ 允许程序员自定义某些运算符的行为,其基本语法如下:

返回类型 operator运算符(参数) {
    // 运算符功能的实现
}

示例:重载 + 运算符

#include <iostream>

class Number {
public:
    int value;

    Number(int v) : value(v) {}

    // 重载加法运算符
    Number operator+(const Number& other) {
        return Number(this->value + other.value);
    }
};

int main() {
    Number n1(5), n2(10);
    Number result = n1 + n2;
    std::cout << "结果: " << result.value << std::endl;
    return 0;
}

📌 解析

  • operator+Number 类支持 + 运算。
  • 该运算符的参数是 另一个 Number 对象
  • 返回一个新的 Number 对象。

3. 友元函数 vs. 成员函数

C++ 提供 两种方式 来重载运算符:

  • 成员函数this 指针)
  • 友元函数(访问 private 成员)

3.1 使用成员函数重载

成员函数的运算符重载:

  • 左侧必须是当前类的对象
  • 右侧参数是另一个类对象或普通类型
class Number {
public:
    int value;
    Number(int v) : value(v) {}

    // 成员函数重载 `+`
    Number operator+(const Number& other) {
        return Number(this->value + other.value);
    }
};

3.2 使用友元函数重载

友元函数可以访问私有成员变量,适用于:

  • 左侧不是当前类对象
  • 需要访问私有成员
#include <iostream>

class Number {
private:
    int value;
public:
    Number(int v) : value(v) {}

    // 友元函数重载 `+`
    friend Number operator+(const Number& a, const Number& b);

    // 友元函数重载 `<<` 让 cout 支持 Number 类型
    friend std::ostream& operator<<(std::ostream& out, const Number& num);
};

// `+` 运算符的友元函数
Number operator+(const Number& a, const Number& b) {
    return Number(a.value + b.value);
}

// `<<` 运算符的友元函数
std::ostream& operator<<(std::ostream& out, const Number& num) {
    out << num.value;
    return out;
}

int main() {
    Number n1(10), n2(20);
    Number sum = n1 + n2;
    std::cout << "Sum: " << sum << std::endl;
    return 0;
}

📌 友元函数 vs. 成员函数

方式优点缺点
成员函数适用于 a + b,左侧是类对象不能用于 5 + a
友元函数适用于 a + b5 + a破坏封装性(访问 private)

4. 常见的运算符重载

4.1 重载 ==!=

如果我们希望对象能够进行 比较,可以重载 ==!=

#include <iostream>

class Number {
public:
    int value;

    Number(int v) : value(v) {}

    // 重载 `==`
    bool operator==(const Number& other) const {
        return this->value == other.value;
    }

    // 重载 `!=`
    bool operator!=(const Number& other) const {
        return !(*this == other);
    }
};

int main() {
    Number n1(10), n2(20);
    if (n1 == n2) {
        std::cout << "相等" << std::endl;
    } else {
        std::cout << "不相等" << std::endl;
    }
    return 0;
}

📌 重载 == 的注意事项

  • operator== 通常与 != 一起重载,避免重复代码。
  • const 关键字确保不会修改对象

4.2 重载 <<cout 支持对象

默认情况下,cout << 对象 不会工作,需要重载 <<

#include <iostream>

class Number {
public:
    int value;
    Number(int v) : value(v) {}

    // 友元函数重载 `<<`
    friend std::ostream& operator<<(std::ostream& out, const Number& num);
};

// `<<` 运算符的友元函数
std::ostream& operator<<(std::ostream& out, const Number& num) {
    out << "Number: " << num.value;
    return out;
}

int main() {
    Number n(100);
    std::cout << n << std::endl;
    return 0;
}

📌 解析

  • << 必须返回 std::ostream&,支持链式输出cout << obj << endl;)。
  • 推荐使用友元函数,避免修改 ostream 类。

5. 运算符重载的注意事项

🚨 不是所有运算符都能重载

  • .(成员访问)
  • .*(成员指针访问)
  • sizeof(获取大小)
  • typeid(类型识别)

🚨 不要滥用运算符重载

  • 仅在 语义明确 时使用(如 + 适用于数学类)。
  • 避免 修改原生运算符的逻辑,避免代码可读性变差。

6. 总结

运算符重载的基本语法
成员函数 vs. 友元函数
常见的运算符重载(+、==、<<)
运算符重载的注意事项

🎯 运算符重载是 C++ 面向对象编程 的重要特性,为自定义类型带来更自然的操作方式。

在下一篇 C++学习系列(8) 中,我们将学习 C++的智能指针(shared_ptr, unique_ptr),敬请期待!🚀


💡 如果你喜欢这篇文章,欢迎点赞、收藏,并关注本系列!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值