- 运算符重载:
- 主要作用:实现类对象之间的运算;
- 隐式调用和显式调用;
- 类内部进行运算符重载只需要一个参数,因为类对象本身就是一个参数;
- 规则:
- 运算符重载不允许发明新的运算符;
- 不能改变运算符操作对象的个数;
- 运算符被重载后,其优先级和结合性不会改变;
- 不能重载的运算符:
-
-
Complex.h
#ifndef COMPLEX_H
#define COMPLEX_H
class Complex{
public:
Complex();
Complex(int real,int img);
~Complex();
// friend Complex operator+ (Complex &a,Complex &b);
Complex operator+ (Complex &a);
// friend Complex operator- (Complex &a,Complex &b);
Complex operator- (Complex &a);
Complex operator++ ();
Complex operator++ (int);
Complex operator-- ();
Complex operator-- (int);
Complex operator= (Complex &a);
void cprintf();
private:
int real;
int img;
};
#endif
Complex.cpp
#include "Complex.h"
#include <iostream.h>
Complex::Complex()
{
this->real = 0;
this->img = 0;
}
Complex::Complex(int real,int img)
{
this->real = real;
this->img = img;
}
Complex::~Complex()
{
}
void Complex::cprintf()
{
cout<<"值为:"<<this->real<<"+"<<this->img<<endl;
}
Complex Complex::operator+ (Complex &a)
{
this->real += a.real;
this->img += a.img;
return *this;
}
Complex Complex::operator- (Complex &a)
{
this->real -= a.real;
this->img -= a.img;
return *this;
}
Complex Complex::operator++ ()//前置++
{
this->real ++;
this->img ++;
return *this;
}
Complex Complex::operator++ (int)//后置++
{
Complex a = *this;
this->real ++;
this->img ++;
return a;
}
Complex Complex::operator-- ()//前置--
{
this->real --;
this->img --;
return *this;
}
Complex Complex::operator-- (int)//后置--
{
Complex a = *this;
this->real --;
this->img --;
return a;
}
Complex Complex::operator= (Complex &a)//=
{
this->real = a.real;
this->img = a.img;
return *this;
}
调用:
Complex a(1,2);
Complex b(2,3);
Complex c;
c = a+b;
c.cprintf();
c = a-b;
c.cprintf();
a++;
a.cprintf();
++a;
a.cprintf();
a--;
a.cprintf();
--a;
a.cprintf();
a = b;
a.cprintf();
输出: