Cześć
Na potrzeby programu muszę w poprawny sposób wypisywać liczby zespolone do czego mam się posłużyć funkcjami zaprzyjaźnionymi przeciążającymi operatory << i >> .
Poniżej podsyłam kod.
Protoyp:
#ifndef COMPLEX_H_
#define COMPLEX_H_
class Complex
{
private:
double re, im;
public:
Complex(double real = 1.0, double imaginary = 1.0);
Complex operator+(const Complex obj_temp);
Complex operator-(const Complex obj_temp);
Complex operator*(const Complex obj_temp);
friend Complex operator*(double value, const Complex obj_temp);
Complex operator~();
friend std::istream & operator>>(std::istream & is, const Complex & number);
friend std::ostream & operator<<(std::ostream & is, const Complex & number);
~Complex();
};
#endif
Implementacja:
#include <iostream>
#include "complex0.h"
Complex::Complex(double real, double imaginary)
{
re = real;
im = imaginary;
}
Complex Complex::operator+(const Complex obj_temp)
{
Complex temp;
temp.re = re + obj_temp.re;
temp.im = im + obj_temp.im;
return temp;
}
Complex Complex::operator-(const Complex obj_temp)
{
Complex temp;
temp.re = re - obj_temp.re;
temp.im = im - obj_temp.im;
return temp;
}
Complex Complex::operator*(const Complex obj_temp)
{
Complex temp;
temp.re = (re * obj_temp.re) - (im * obj_temp.im);
temp.im - (re * obj_temp.im) + (im * obj_temp.re);
return temp;
}
Complex operator*(double value, const Complex obj_temp)
{
Complex temp;
temp.re = value * obj_temp.re;
temp.im = value * obj_temp.im;
return temp;
}
Complex Complex::operator~()
{
im = -im;
}
std::istream & operator>>(std::istream & is, const Complex & number)
{
using std::endl;
using std::cout;
cout << "Skladowa rzeczywista: ";
while( !(is >> number.re) )
{
is.clear();
while( is.get() != '\n' )
continue;
cout << "ERROR! Try again!" << endl;
cout << "Skladowa rzeczywista: ";
}
std::cout << "Skladowa urojona: ";
while( !(is >> number.im) )
{
is.clear();
while( is.get() != '\n' )
continue;
cout << "ERROR! Try again!" << endl;
cout << "Skladowa urojona: ";
}
return is;
}
std::ostream & operator<<(std::ostream & os, const Complex & number)
{
using std::cout;
using std::endl;
os << "(" << number.re << ", " << number.im << "i)" << endl;
return os;
}
Complex::~Complex()
{
}
main.cpp
#include <iostream>
#include "complex0.h"
int main()
{
using namespace std;
Complex a(3.0, 4.0);
Complex c;
cout << "Podaj liczbe zespolona (k, ab zakonczyc):\n";
cin >> c;
cout << "c to " << c << '\n';
cout << "Sprzezona z c to " << ~c << '\n';
cout << "a to " << a << '\n';
cout << "a + c wynosi " << a + c << '\n';
cout << "a - c wynosi " << a - c << '\n';
cout << "a * c wynosi " << a * c << '\n';
cout << "2 * c wynosi " << 2 * c << '\n';
cout << "KONIEC";
return 0;
}
Po skompilowaniu i odpaleniu powstaje nieskończona pętla, która cały czas powtarza komunikat "składowa rzeczywista". Tak więc problem najpewniej tkwi w mojej imlementacji obydwu funkcji zaprzyjaźnionych.
Z góry dziękuję za odpowiedzi. :)