21xrx.com
2024-11-22 05:30:37 Friday
登录
文章检索 我的文章 写文章
C++重载运算符:拓展你的代码功能
2023-07-07 22:33:04 深夜i     --     --
C++ 重载运算符 代码 功能 拓展

C++是一门强大的编程语言,它支持很多高级的编程技术。其中,函数重载和运算符重载是C++中重要的编程技术之一。函数重载允许程序员定义多个同名函数,这些函数的参数列表不同,使得程序的可读性更高。而运算符重载则是让程序员能够自定义运算符的行为。

C++中的运算符重载,允许程序员重载各种运算符,包括算术运算符、逻辑运算符、比较运算符等等。我们可以通过重载运算符,让它们适用于自己定义的数据类型,比如向量、矩阵等。运算符重载使得代码更加清晰、简洁、易于维护。

以绝对值运算符为例,C++中的绝对值函数是abs(),只能用来求int、long、double、float等数据类型的绝对值。如果我们要求一个自定义类型的绝对值,就需要使用运算符重载技术,让这个类型支持绝对值运算符。代码示例如下:


#include <iostream>

#include <cstdlib>

using namespace std;

class Complex

{

public:

  double real, imag;

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

  double abs()const{return sqrt(real * real + imag * imag);}

  Complex operator -()const{return Complex(-real, -imag);}

  bool operator ==(const Complex& c)constreturn real == c.real && imag == c.imag;

  bool operator !=(const Complex& c)const{return real != c.real || imag != c.imag;}

  Complex operator +(const Complex& c)const{return Complex(real + c.real, imag + c.imag);}

  Complex operator -(const Complex& c)const{return Complex(real - c.real, imag - c.imag);}

  Complex operator *(const Complex& c)const{return Complex(real * c.real - imag * c.imag, real * c.imag + imag * c.real);}

  Complex operator /(const Complex& c)const;

};

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

{

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

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

}

int main(int argc, char* argv[])

{

  Complex c1(3, 4), c2(5, 6), c3(3, 4);

  cout << "c1 abs:" << c1.abs() << endl;//c1 abs:5

  cout << "c2 abs:" << c2.abs() << endl;//c2 abs:7.81026

  Complex c4 = -c1;//-c1:(-3,-4)

  cout << "-c1:(" << c4.real << "," << c4.imag << ")" << endl;

  cout << "c1 == c3:" << (c1 == c3) << endl;//c1 == c3:1

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

  Complex c5 = c1 + c2;//c1 + c2:(8,10)

  cout << "c1 + c2:(" << c5.real << "," << c5.imag << ")" << endl;

  Complex c6 = c1 - c2;//c1 - c2:(-2,-2)

  cout << "c1 - c2:(" << c6.real << "," << c6.imag << ")" << endl;

  Complex c7 = c1 * c2;//c1 * c2:(-9,38)

  cout << "c1 * c2:(" << c7.real << "," << c7.imag << ")" << endl;

  Complex c8 = c1 / c2;//c1 / c2:(0.639344,0.0327879)

  cout << "c1 / c2:(" << c8.real << "," << c8.imag << ")" << endl;

  return 0;

}

在这个例子中,我们定义了一个复数类Complex,重载了减法运算符、一元负号运算符、相等运算符、不等运算符、加法运算符、减法运算符、乘法运算符、除法运算符。除法运算符的重载比较特殊,需要定义一个成员函数。

通过运算符重载,我们可以更加自然地使用自定义类型的运算符,代码可读性更强,具有更高的表现力。因此,对于C++编程来说,合理使用运算符重载技术,可以拓展代码的功能,提高代码的复用性和可读性。

  
  

评论区

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