21xrx.com
2024-09-19 23:53:35 Thursday
登录
文章检索 我的文章 写文章
C++运算符重载示例代码
2023-07-06 17:59:49 深夜i     --     --
C++ 运算符重载 示例代码

C++是一门强类型语言,它支持通过运算符重载来增强程序的灵活性和扩展性。重载运算符是指为一个已经存在的运算符重新定义一个行为。这样,在程序中就能够像使用内置运算符一样使用自定义的运算符,从而实现更加复杂的功能。

下面是一个C++运算符重载的示例代码,可以让我们更好地理解运算符重载的实现过程。


#include <iostream>

using namespace std;

class Complex {

private:

  double real; // 复数的实部

  double imag; // 复数的虚部

public:

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

  Complex operator + (const Complex& c) const; // “+”运算符重载

  Complex operator - (const Complex& c) const; // “-”运算符重载

  Complex operator * (const Complex& c) const; // “*”运算符重载

  Complex operator / (const Complex& c) const; // “/”运算符重载

  friend ostream& operator << (ostream& os, const Complex& c); // “<<”运算符重载

};

Complex Complex::operator+ (const Complex& c) const {

  return Complex(real + c.real, imag + c.imag);

}

Complex Complex::operator- (const Complex& c) const {

  return Complex(real - c.real, imag - c.imag);

}

Complex Complex::operator* (const Complex& c) const {

  return Complex(real * c.real - imag * c.imag, real * c.imag + imag * c.real);

}

Complex Complex::operator/ (const Complex& c) const {

  double denominator = c.real * c.real + c.imag * c.imag;

  return Complex((real * c.real + imag * c.imag) / denominator, (imag * c.real - real * c.imag) / denominator);

}

ostream& operator<<(ostream& os, const Complex& c) {

  os << c.real << " + " << c.imag << "i";

  return os;

}

int main() {

  Complex c1(1, 2), c2(3, 4);

  Complex c3 = c1 + c2;

  Complex c4 = c1 - c2;

  Complex c5 = c1 * c2;

  Complex c6 = c1 / c2;

  cout << "c1 = " << c1 << endl;

  cout << "c2 = " << c2 << endl;

  cout << "c1 + c2 = " << c3 << endl;

  cout << "c1 - c2 = " << c4 << endl;

  cout << "c1 * c2 = " << c5 << endl;

  cout << "c1 / c2 = " << c6 << endl;

  return 0;

}

在上面的代码中,我们定义了一个复数类`Complex`,并重载了`+`、`-`、`*`、`/`、`<<`这几个运算符,实现了复数运算的功能。

在运行程序时,我们可以看到以下输出结果:


c1 = 1 + 2i

c2 = 3 + 4i

c1 + c2 = 4 + 6i

c1 - c2 = -2 - 2i

c1 * c2 = -5 + 10i

c1 / c2 = 0.44 + 0.08i

从输出结果可以看出,我们成功地实现了复数的基本运算,并且以自定义的形式输出了复数的值。

总之,C++运算符重载功能为我们提供了更好的灵活性和扩展性,在实际开发中,我们可以通过这种方式,自定义实现各种运算符的功能,让程序变得更加强大。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复