21xrx.com
2025-07-07 15:48:04 Monday
文章检索 我的文章 写文章
C++中的加法运算符重载
2023-06-29 09:02:28 深夜i     19     0
C++ 加法运算符 重载

C++ 中的运算符重载功能使我们可以为类定义自定义行为,这样类的使用者就可以通过重载运算符来进行自定义运算。

在 C++ 中,我们可以通过重载运算符来定义两个对象之间的加法运算。下面是一份加法运算符重载的示例代码:

#include<iostream>
using namespace std;
class Complex
{
private:
  float real, imag;
public:
  Complex(float r=0, float i=0):real(r), imag(i){}
  Complex operator + (Complex const &obj)
  {
    Complex res;
    res.real = real + obj.real;
    res.imag = imag + obj.imag;
    return res;
  }
  void display()
  {
    cout<<real<<" + "<<imag<<"i"<<endl;
  }
};
int main()
{
  Complex c1(2, 3), c2(4, 5);
  Complex c3 = c1 + c2;
  c3.display();
  return 0;
}

在上面的示例代码中,我们定义了一个 Complex 类,该类具有实部 和虚部,重载了加法运算符。加法运算符重载函数如下:

Complex operator + (Complex const &obj)
{
  Complex res;
  res.real = real + obj.real;
  res.imag = imag + obj.imag;
  return res;
}

该函数接受一个 Complex 类对象作为参数,通过将当前对象的实部和虚部与传入对象的实部和虚部相加,创建一个新的 Complex 类对象。然后,我们可以使用该运算符来执行两个复数相加,并输出结果。

在主函数中,我们创建了两个复数对象,c1 和 c2,并将它们相加,将结果保存在 c3 中。然后使用 display() 函数输出结果。

总的来说,运算符重载是 C++ 的一种非常有用的功能,可以使我们将复杂的操作简化为简单的语法,这样代码的可读性和可维护性将得到很大的提升。

  
  
下一篇: C++实现定时器

评论区