C++运算符重载(成员函数)

C++语言对运算符重载制定了一下规则:绝大部分运算符都能被重载,不能重载的运算符只有一下几个:成员访问运算符'.';成员指针访问运算符'.*';作用域运算符'::';长度运算符'sizeof';条件运算符'?:'。

在C++中,运算符重载可以通过成员函数或非成员函数(通常是友元函数)来实现。是否需要参数列表取决于运算符的类型和它是作为成员函数还是非成员函数来重载的。

一元运算符

一元运算符包括前置和后置自增、自减、取反等。

  • 前置运算符:如++(前置自增)、--(前置自减)、-(取负)、!(逻辑非)。

作为成员函数重载时,不需要参数。

class MyClass {
public:
    MyClass& operator++() { // 前置自增运算符重载为成员函数
        // 增加逻辑
        return *this;
    }
};
  • 后置运算符:如++(后置自增)、--(后置自减),需要一个int类型的哑参数来区分前置和后置。
class MyClass {
public:
    MyClass operator++(int) { // 后置自增运算符重载为成员函数
        MyClass temp = *this;
        // 增加逻辑
        return temp;
    }
};

二元运算符

二元运算符包括加法、减法、乘法、除法、赋值等。成员函数在重载时会隐含地操作当前对象作为第一个操作数。如 FunNumber operator-(); int operator-(FunNumber);FunNumber operator-(int);

  • 作为成员函数重载时,需要一个参数,该参数表示右操作数。
    class MyClass {
    public:
        MyClass operator+(const MyClass& other) const { // 加法运算符重载为成员函数
            MyClass result;
            // 加法逻辑
            return result;
        }
    };
    

    示例说明

    假设我们有一个类Complex,用于表示复数,并希望重载二元运算符。

1. 加法运算符 (+)
class Complex {
public:
    double real, imag;

    Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {}

    // 成员函数重载加法运算符
    Complex operator+(const Complex& rhs) const {
        return Complex(real + rhs.real, imag + rhs.imag);
    }
};
  • 2. 减法运算符 (-
class Complex {
public:
    double real, imag;

    Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {}

    // 成员函数重载减法运算符
    Complex operator-(const Complex& rhs) const {
        return Complex(real - rhs.real, imag - rhs.imag);
    }
};
3.乘法运算符 (*) 
class Complex {
public:
    double real, imag;

    Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {}

    // 成员函数重载乘法运算符
    Complex operator*(const Complex& rhs) const {
        return Complex(real * rhs.real - imag * rhs.imag, real * rhs.imag + imag * rhs.real);
    }
};
4.除法运算符 (/) 
class Complex {
public:
    double real, imag;

    Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {}

    // 成员函数重载除法运算符
    Complex operator/(const Complex& rhs) const {
        double denom = rhs.real * rhs.real + rhs.imag * rhs.imag;
        return Complex((real * rhs.real + imag * rhs.imag) / denom, (imag * rhs.real - real * rhs.imag) / denom);
    }
};
 5.赋值运算符 (=)
class Complex {
public:
    double real, imag;

    Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {}

    // 成员函数重载赋值运算符
    Complex& operator=(const Complex& rhs) {
        if (this == &rhs) return *this; // 自我赋值检查
        real = rhs.real;
        imag = rhs.imag;
        return *this;
    }
};

对于赋值运算符,由于它需要修改左操作数,只能作为成员函数重载。其他二元运算符可以选择成员函数形式或非成员函数形式进行重载。

  • 11
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值