вопросы / 9.Правила перегрузки операций
.rtf9) Перегрузка операций.
class Point
{double x,y;
public:
Point operator+(Point&)
(return Point (x+px,y+py);}}
<тип> operator <знак операций>
(<список параметров>) {тело функций}
↑//первый вариант описания перегрузки операций
↓//второй вариант описания перегрузки операций
Friend Point::operator +(Point&; Point&)};
Point operator+(Point&p1,Point&p2)
{return Point
(p1.x+p2.x;p1.y+p2.y);}
_________
Point p3=p1+p2;
p3=p1.operator+(p2);
Если 1 операнд имеет базовый тип, то перегрузка возможна лишь в виде внешней функции
class monstr {
public::
monstr&operator ++( )
{++health;
Return*this;}};
monstr V;
cout<<(++V);
get_health ():
Постифксные опер. имеют параметр типа int
Monstr &operator ++(int)↓
{monstr M(*this);
health++;
return M;
}
cout<<(V++).get_health
Операция “больше” bool
bool operator>(const monstr &M)
{return (health>M.health)}
↑//Внутри класса
↓//Описыв.внешне
bool operator >(const monstr &M1, const monstr &M2)
{return (M1.get_health ()>M2.get_health ( );}