C++之操作符重载(+、-、*、/、=、==、!=)

本文介绍了C++中操作符重载的意义、语法及具体实现,包括如何将操作符重载为全局函数和成员函数,并提供了复数类的示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、操作符重载的意义

  C++中重载操作符能够扩展操作符的功能,操作符重载是以函数的方式进行的。其实操作符重载的本质为用特殊形式的函数扩展操作符的功能。

二、操作符重载的语法

  重载操作符时是通过operator关键字来定义特殊的函数,其本质是通过函数重载操作符。其语法规则如下:

Type operator Sign(const Type& p1, const Type& p2)
{
    Type ret;

    return ret;
}

Sign为系统中预定义的操作符,如:+、-、*、/,等
三、操作符重载具体实现

  操作符重载函数可以是全局函数,也可以是成员函数,下面分别给出实现:
  
1.重载为全局函数
  重载为全局函数时,必须给出所有的操作数。当然,全局函数也可以作为友元函数。下面代码为通过友元函数重载复数类的“+”操作符:
  

#include <stdio.h>

class Complex 
{
    int a;
    int b;
public:
    Complex(int a = 0, int b = 0)
    {
        this->a = a;
        this->b = b;
    }

    int getA()
    {
        return a;
    }

    int getB()
    {
        return b;
    }

    friend Complex operator + (const Complex& p1, const Complex& p2);
};

Complex operator + (const Complex& p1, const Complex& p2)
{
    Complex ret;

    ret.a = p1.a + p2.a;
    ret.b = p1.b + p2.b;

    return ret;
}

int main()
{

    Complex c1(1, 2);
    Complex c2(3, 4);
    Complex c3 = c1 + c2; // operator + (c1, c2)

    printf("c3.a = %d, c3.b = %d\n", c3.getA(), c3.getB());

    return 0;
}

运行结果如下:

这里写图片描述

  下面给出复数类“==”和“!=”操作符非友元全局函数重载:

#include <iostream>

using namespace std;

class Complex
{
    double m_a;
    double m_b;
public:
    Complex(double a = 0, double b = 0)
    {
        m_a = a;
        m_b = b;
    }
    double getA() const
    {
        return m_a;
    }
    double getB() const
    {
        return m_b;
    }
};

bool operator == (const Complex& l, const Complex& r)
{
    return (l.getA() == r.getA()) && (l.getB() == l.getB());
}
bool operator != (const Complex& l, const Complex& r)
{
    return !(l == r);
}

int main()
{
    Complex c1(1, 2);
    Complex c2(1, 2);

    cout << "(c1 == c2) : " << (c1 == c2) << endl;
    cout << "(c1 != c2) : " << (c1 != c2) << endl;

    return 0;
}

运行结果如下所示:

这里写图片描述

2.重载为成员函数
   操作符重载为成员函数时,比重载为全局操作符重载函数少一个参数(左操作数为this指针),编译器优先在成员函数中寻找操作符重载函数。下面给出复数类各操作符重载为成员函数的代码:
  
Complex.h

#ifndef _COMPLEX_H_
#define _COMPLEX_H_

class Complex
{
    double a;
    double b;
public:
    Complex(double a = 0, double b = 0);
    double getA();
    double getB();
    double getModulus();

    Complex operator + (const Complex& c);
    Complex operator - (const Complex& c);
    Complex operator * (const Complex& c);
    Complex operator / (const Complex& c);

    bool operator == (const Complex& c);
    bool operator != (const Complex& c);

    Complex& operator = (const Complex& c);
};

#endif

Complex.cpp

#include "Complex.h"
#include "math.h"

Complex::Complex(double a, double b)
{
    this->a = a;
    this->b = b;
}

double Complex::getA()
{
    return a;
}

double Complex::getB()
{
    return b;
}

double Complex::getModulus()
{
    return sqrt(a * a + b * b);
}

// 重载+操作符
Complex Complex::operator + (const Complex& c)
{
    double na = a + c.a;
    double nb = b + c.b;
    Complex ret(na, nb);

    return ret;
}

// 重载-操作符
Complex Complex::operator - (const Complex& c)
{
    double na = a - c.a;
    double nb = b - c.b;
    Complex ret(na, nb);

    return ret;
}

// 重载*(乘法)操作符
Complex Complex::operator * (const Complex& c)
{
    double na = a * c.a - b * c.b;
    double nb = a * c.b + b * c.a;
    Complex ret(na, nb);

    return ret;
}

// 重载/(除法)操作符
Complex Complex::operator / (const Complex& c)
{
    double cm = c.a * c.a + c.b * c.b;
    double na = (a * c.a + b * c.b) / cm;
    double nb = (b * c.a - a * c.b) / cm;
    Complex ret(na, nb);

    return ret;
}

// 重载==操作符
bool Complex::operator == (const Complex& c)
{
    return (a == c.a) && (b == c.b);
}

// 重载!=操作符
bool Complex::operator != (const Complex& c)
{
    return !(*this == c);
}

// 重载=(赋值)操作符
Complex& Complex::operator = (const Complex& c)
{
    if( this != &c )
    {
        a = c.a;
        b = c.b;
    }

    return *this;
}

main.cpp

#include <stdio.h>
#include "Complex.h"

int main()
{
    Complex c1(1, 2);
    Complex c2(3, 6);
    Complex c3 = c2 - c1;
    Complex c4 = c1 * c3;
    Complex c5 = c2 / c1;

    printf("c3.a = %f, c3.b = %f\n", c3.getA(), c3.getB());
    printf("c4.a = %f, c4.b = %f\n", c4.getA(), c4.getB());
    printf("c5.a = %f, c5.b = %f\n", c5.getA(), c5.getB());

    Complex c6(2, 4);

    printf("c3 == c6 : %d\n", c3 == c6);
    printf("c3 != c4 : %d\n", c3 != c4);

    (c3 = c2) = c1;

    printf("c1.a = %f, c1.b = %f\n", c1.getA(), c1.getB());
    printf("c2.a = %f, c2.b = %f\n", c2.getA(), c2.getB());
    printf("c3.a = %f, c3.b = %f\n", c3.getA(), c3.getB());

    return 0;
}

运行结果如下:

这里写图片描述

四、注意事项

  1.C++规定,赋值操作符“=”只能重载为成员函数;
  2.操作符重载不能改变原操作符的优先级
  3.操作符重载不能改变操作数的个数
  4.操作符重载不能改变操作符的原有语义

### C++ 复数类运算符重载实现加减乘除 以下是完整的 `Complex` 类代码示例,实现了复数与复数之间以及复数与整数之间的加法 (`+`)、减法 (`-`)、乘法 (`*`) 和除法 (`/`) 运算符重载: ```cpp #include <iostream> using namespace std; class Complex { public: // 构造函数 Complex(double real = 0, double imag = 0) : real(real), imag(imag) {} // 加法运算符重载 (复数 + 复数) Complex operator+(const Complex& other) const { return Complex(this->real + other.real, this->imag + other.imag); } // 减法运算符重载 (复数 - 复数) Complex operator-(const Complex& other) const { return Complex(this->real - other.real, this->imag - other.imag); } // 乘法运算符重载 (复数 * 复数) Complex operator*(const Complex& other) const { double newReal = this->real * other.real - this->imag * other.imag; double newImag = this->real * other.imag + this->imag * other.real; return Complex(newReal, newImag); } // 除法运算符重载 (复数 / 复数) Complex operator/(const Complex& other) const { double denominator = other.real * other.real + other.imag * other.imag; if (denominator == 0) throw runtime_error("Division by zero"); double newReal = (this->real * other.real + this->imag * other.imag) / denominator; double newImag = (this->imag * other.real - this->real * other.imag) / denominator; return Complex(newReal, newImag); } // 加法运算符重载 (复数 + 整数) Complex operator+(int num) const { return Complex(this->real + num, this->imag); } // 减法运算符重载 (复数 - 整数) Complex operator-(int num) const { return Complex(this->real - num, this->imag); } // 乘法运算符重载 (复数 * 整数) Complex operator*(int num) const { return Complex(this->real * num, this->imag * num); } // 除法运算符重载 (复数 / 整数) Complex operator/(int num) const { if (num == 0) throw runtime_error("Division by zero"); return Complex(this->real / num, this->imag / num); } // 友元函数:整数 + 复数 friend Complex operator+(int num, const Complex& c); // 友元函数:整数 - 复数 friend Complex operator-(int num, const Complex& c); // 友元函数:整数 * 复数 friend Complex operator*(int num, const Complex& c); // 友元函数:整数 / 复数 friend Complex operator/(int num, const Complex& c); // 打印方法 void print() const { cout << real << "+" << imag << "i" << endl; } private: double real; // 实部 double imag; // 虚部 }; // 友元函数实现 Complex operator+(int num, const Complex& c) { return Complex(num + c.real, c.imag); } Complex operator-(int num, const Complex& c) { return Complex(num - c.real, -c.imag); } Complex operator*(int num, const Complex& c) { return Complex(c.real * num, c.imag * num); } Complex operator/(int num, const Complex& c) { double denominator = c.real * c.real + c.imag * c.imag; if (denominator == 0) throw runtime_error("Division by zero"); return Complex((num * c.real) / denominator, -(num * c.imag) / denominator); } int main() { Complex c1(3, 5); // 初始化复数 c1: 3 + 5i Complex c2(2, 7); // 初始化复数 c2: 2 + 7i // 测试复数间的加法 Complex c3 = c1 + c2; cout << "c1 + c2 = "; c3.print(); // 测试复数间的减法 Complex c4 = c1 - c2; cout << "c1 - c2 = "; c4.print(); // 测试复数间的乘法 Complex c5 = c1 * c2; cout << "c1 * c2 = "; c5.print(); // 测试复数间的除法 try { Complex c6 = c1 / c2; cout << "c1 / c2 = "; c6.print(); } catch (runtime_error& e) { cerr << e.what() << endl; } // 测试复数与整数的加法 Complex c7 = c1 + 4; cout << "c1 + 4 = "; c7.print(); // 测试复数与整数的减法 Complex c8 = c1 - 4; cout << "c1 - 4 = "; c8.print(); // 测试复数与整数的乘法 Complex c9 = c1 * 4; cout << "c1 * 4 = "; c9.print(); // 测试复数与整数的除法 try { Complex c10 = c1 / 4; cout << "c1 / 4 = "; c10.print(); } catch (runtime_error& e) { cerr << e.what() << endl; } // 测试整数与复数的加法 Complex c11 = 4 + c1; cout << "4 + c1 = "; c11.print(); // 测试整数与复数的减法 Complex c12 = 4 - c1; cout << "4 - c1 = "; c12.print(); // 测试整数与复数的乘法 Complex c13 = 4 * c1; cout << "4 * c1 = "; c13.print(); // 测试整数与复数的除法 try { Complex c14 = 4 / c1; cout << "4 / c1 = "; c14.print(); } catch (runtime_error& e) { cerr << e.what() << endl; } return 0; } ``` #### 解析 1. **构造函数**: 提供默认初始化以及自定义实部和虚部的初始化[^1]。 2. **加法运算符重载**: 支持复数间及复数与整数的加法操作。对于后者,通过友元函数实现反向操作[^1]。 3. **减法运算符重载**: 同理支持复数间及复数与整数的减法操作。 4. **乘法运算符重载**: 遵循复数乘法规则 `(a+bi)(c+di)=(ac-bd)+(ad+bc)i`,并扩展至整数情况。 5. **除法运算符重载**: 利用共轭原理计算复数除法 `(a+bi)/(c+di)`,同样处理整数情况下的特殊逻辑[^1]。 --- ###
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值