题目概述:
定义一个复数类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;
}
上机实践:
相关文章
- 08-29Python之__slots__ &运算符重载反向运算
- 08-29c++中派生类对基类成员的三种访问规则(转)
- 08-29C++函数调用运算符 函数对象 函数指针
- 08-29友元函数的运算符重载operator+
- 08-29C++学习笔记-1-自增和自减运算符
- 08-29c++重载与覆写
- 08-29自加运算符的前置与后置的重载
- 08-29C++ Primer 有感(重载操作符)
- 08-29运算符重载
- 08-29C++重写与重载、重定义