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++:对运算符重载

上一篇:openh264-当前是否编I帧


下一篇:Git自学笔记001_Real(版本控制、版本迭代)