复数运算,就显示>>没有与这些操作数匹配的“>>"的运算符
头文件#ifndef COMPLEX_H_
#define COMPLEX_H_
#include<iostream>
namespace COMPLEX
{
class Complex
{
private:
double real;
double imaginary;
public:
Complex();
Complex(double a_real, double b_imaginary);
~Complex();
Complex operator+(const Complex& a)const;
Complex operator-(const Complex& a)const;
Complex operator*(const Complex& a)const;
Complex operator*(double m)const;
Complex operator-()const;
friend Complex operator*(double m, const Complex& a);
friend std::ostream& operator<<(std::ostream& os, const Complex& a);
friend std::istream& operator>>(std::istream& os, const Complex& a);
};
}
#endif
源代码1
#include"stack.h"
#include<iostream>
namespace COMPLEX
{
Complex::Complex()
{
real = imaginary = 0;
}
Complex::Complex(double a_real, double b_imaginary)
{
real = a_real;
imaginary = b_imaginary;
}
Complex::~Complex()
{
}
Complex Complex::operator+(const Complex& a)const
{
Complex temp;
temp.real = real + a.real;
temp.imaginary = imaginary + a.imaginary;
return temp;
}
Complex Complex::operator-(const Complex& a)const
{
Complex temp;
temp.real = real - a.real;
temp.imaginary = imaginary - a.imaginary;
return temp;
}
Complex Complex::operator*(const Complex& a)const
{
Complex temp;
temp.real = real * a.real- imaginary * a.imaginary;
temp.imaginary =real*a.imaginary+imaginary*a.real;
return temp;
}
Complex Complex:: operator-()const
{
return Complex(real, -imaginary);
}
Complex Complex::operator*(double m)const
{
Complex temp;
temp.real = real * m;
temp.imaginary = imaginary * m;
return temp;
}
Complex operator*(double m, const Complex& a)
{
return a * m;
}
std::ostream& operator<<(std::ostream& os, const Complex& a)
{
os << a.real<<","<<a.imaginary<<"i"<<std::endl;
return os;
}
std::istream& operator>>(std::istream& is, const Complex& a)
{
std::cout << "real:";
if (!(is >> a.real))
return is;
std::cout << "imaginary:";
is >> a.imaginary;
return is;
}
}
源代码2
#include<iostream>
#include"stack.h"
int main()
{
COMPLEX::Complex a(3.0, 4.0);
COMPLEX::Complex c;
std::cout << "Enter a complex number(q to quit):\n";
while (std::cin >> c)
{
std::cout << "c is " << c << '\n';
std::cout << "complex conjugate is" << -c << '\n';
std::cout << "a is " << a << '\n';
std::cout << "a+c is " << a + c << '\n';
std::cout << "a-c is " << a - c << '\n';
std::cout << "a*c is " << a * c << '\n';
std::cout << "2*c is " << 2 * c << '\n';
std::cout << "Enter a complex number(q to quit):\n";
}
std::cout << "Done!\n";
return 0;
}