完成複數類的加、乘等簡單運算。首先會初始化一個複數,然後需要你重新輸入一個複數,然後進行簡單的運算,最後兩個複數進行比較。其中用到重載運算符,this指針,構造函數等知識。
#define _CRT_SECURE_NO_WARNINGS 1
#ifndef COMPLEX_H
#define COMPLEX_H
#include <iostream>
#include <iomanip>
class Complex
{
public:
Complex(double _real,double _imag = 0.0):real(_real),imag(_imag){}
Complex(std::istream &is){is >> *this;};
void SetReal(double _real);
void SetImag(double _imag);
void SetVal(double _real,double _imag);
inline double GetReal() const;
inline double GetImag() const;
Complex& operator+=(const Complex &val);
Complex& operator*=(const Complex &val);
friend bool operator==(const Complex &lhs,const Complex &rhs);
friend std::istream& operator>>(std::istream &,Complex &);
friend std::ostream& operator<<(std::ostream &,const Complex &);
private:
double real;
double imag;
};
Complex operator+(const Complex &lhs, const Complex &rhs);
Complex operator*(const Complex &lhs, const Complex &rhs);
inline bool operator==(const Complex &lhs,const Complex &rhs)
{
return (lhs.real == rhs.real) && (lhs.imag == rhs.imag);
}
inline bool operator!=(const Complex &lhs,const Complex &rhs)
{
return !(lhs==rhs);
}
inline Complex& Complex::operator+=(const Complex &val)
{
real += val.real;
imag += val.imag;
return *this;
}
inline Complex operator+(const Complex &lhs,const Complex &rhs)
{
Complex ret(lhs);
ret += rhs;
return ret;
}
inline Complex& Complex::operator*=(const Complex &val)
{
double tReal = real;
double tImag = imag;
real = tReal*val.real - tImag*val.imag;
imag = tReal*val.imag + tImag*val.real;
return *this;
}
inline Complex operator*(const Complex &lhs,const Complex &rhs)
{
Complex ret(lhs);
ret *= rhs;
return ret;
}
inline std::istream& operator>>(std::istream &is,Complex &com)
{
std::cout << "請輸入實數部分:" ;
is >> com.real;
if(is)
{
std::cout << "請輸入虛數部分:" ;
is >> com.imag;
if(is)
{
return is;
}
else
{
com = Complex(0.0);
}
}
else
{
com = Complex(0.0);
}
return is;
}
inline std::ostream& operator<<(std::ostream &os, const Complex &com)
{
os << "複數爲:" << com.real << std::showpos << com.imag << "i" << std::endl;
return os;
}
inline double Complex::GetReal() const
{
return real;
}
inline double Complex::GetImag() const
{
return imag;
}
void Complex::SetReal(double _real)
{
real = _real;
}
void Complex::SetImag(double _imag)
{
imag = _imag;
}
void Complex::SetVal(double _real,double _imag)
{
real = _real;
imag = _imag;
}
#endif
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <tchar.h>
#include <cstdlib>
#include <iostream>
#include <sys/timeb.h>
#include <ctime>
#include <climits>
#include "Complex.h"
using namespace std;
int main(int argc, _TCHAR* argv[])
{
Complex c1(3,4);
cout << c1;
Complex c2(cin);
cout << c2;
Complex c3 = c1 + c2;
cout << c3;
Complex c4 = c1*c2;
cout << c4;
Complex c5(3,4);
c5 *= c1;
cout << c5;
if(c1==c2)
{
cout << "複數c1和c2相等" << endl;
}
else
{
cout << "複數c1和c2不等" << endl;
}
system("pause");
return 0;
}