class complex
{
double re,im;
complex& operator= (const complex& rhs);
complex& operator+= (const complex& rhs);
complex& operator-= (const complex& rhs);
complex& operator*= (const complex& rhs);
complex& operator/= (const complex& rhs);
}
...
complex:: operator= (const complex& rhs)
{
re = rhs.re; im = rhs.im; return *this;
}
complex:: operator+= (const complex& rhs)
{
re += rhs.re; im += rhs.im; return *this;
}
complex::operator-= (const complex& rhs)
{
re -= rhs.re; im -= rhs.im; return *this;
}
complex::operator *= (const complex& rhs)
{
double tmp = re*rhs.re-im*rhs.im;
im = im*rhs.re+re*rhs.im;
re = tmp;
return *this;
}
complex::operator /= (const complex& rhs)
{
double denom = rhs.re*rhs.re + rhs.im*rhs.im;
double re1 = (re*rhs.re+im*rhs.im)/denom;
double im1 = (rhs.re*im-re*rhs.im)/denom;
re = re1;
im = im1;
return *this;
}
Пример 5
Для класса "комплексное число" с данными double Re; double Im; выполнить перегрузку операций ввода, вывода, сравнения.
#include <fstream>
using namespace std;
class str
{
private:
char Re;
char Im;
char *content;
public:
str();
str(char[]);
~str();
void operator= (char[]);
friend ofstream& operator> (ifstream&,str&);
};
===================================
#include "./ComplexN.h"
#include <fstream>
using namespace std;
double Re,Im;
str::str()
{
content=new char[1];
content[0]='\0';
}
str::~str()
{
delete []content;
}
str::str(char cont[])
{
size_t newlen=strlen(cont);
content=new char[newlen+1];
strcpy(content,cont);
|
|
}
void str::operator =(char cont[])
{
size_t newlen=strlen(cont);
content=new char[newlen];
strcpy(content,cont);
}
ofstream& operator<<(ofstream& out,str &p)
{
out<<Re<<Im;//какие-нибудь действия
return out;
}
ifstream& operator>>(ifstream& in,str &p)
{
in>>Re>>Im;//какие-нибудь действия
return in;
}
Пример 6
Перегрузка унарных операций (инкримент)
#include <iostream>
using namespace std;
class Counter
{
private:
unsigned int count; // значение счетчика
public:
Counter (): count (0) { } // конструктор
unsigned int get_count () { return count; } // получить значение
void operator++ () { ++count; } // увеличить значение
};
int main ()
{
Counter cl, c2; // определяем переменные
cout << "ncl = " << cl.get_count (); // выводим на экран
cout << "nc2 = " << c2.get_count ();
++cl; // увеличиваем cl
++c2; // увеличиваем c2
++c2; // увеличиваем c2
cout << "ncl = " << cl.get_count (); // снова показываем значения
cout << "nc2 = " << c2.get_count () << endl;
return 0;
}
Арифметические операции