C/C++教程

C++:对运算符重载

本文主要是介绍C++:对运算符重载,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

题目概述:
定义一个复数类Complex,重载运算符“+”,“-” ,“ * ”,“/”,分别求两复数。
编程:
#include< iostream>
using namespace std;
class Complex
{
private:
double real;
double imag;
public:
Complex() { real = 0; imag = 0; }
Complex(double r, double i) { real = r; imag = i; }
Complex operator+(Complex& c2);
Complex operator-(Complex& c2);
Complex operator*(Complex& c2);
Complex operator/(Complex& c2);
void display();
};
void Complex::display()
{
cout << “(” << real << “,” << imag << “i)” << endl;
}
Complex Complex::operator+(Complex& c2)
{
Complex c;
c.real = real + c2.real;
c.imag = imag + c2.imag;
return c;
}
Complex Complex::operator-(Complex& c2)
{
Complex c;
c.real = real - c2.real;
c.imag = imag - c2.imag;
return c;
}
Complex Complex::operator*(Complex& c2)
{
Complex c;
c.real = real * c2.real;
c.imag = imag * c2.imag;
return c;
}
Complex Complex::operator/(Complex& c2)
{
Complex c;
c.real = real / c2.real;
c.imag = imag / c2.imag;
return c;
}
int main()
{
Complex c1(3, 4), c2(5, -10), c3;
c3 = c1 + c2;
cout << “c3=”;
c3.display();
c3 = c1 - c2;
cout << “c3=”;
c3.display();
c3 = c1 * c2;
cout << “c3=”;
c3.display();
c3 = c1 / c2;
cout << “c3=”;
c3.display();
return 0;
}
上机实践:
在这里插入图片描述

这篇关于C++:对运算符重载的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!