++/--运算符
++/- -
operand
,
operand value after operating =
operand
+1/-1,
expresson
value = operand +1/-1
operand
++/- -
,
operand value after operating =
operand +1/-1, expresson
value = operand
重载模板
//Global operator
//Pre operator:
RetType operator “重载运算符”(ArgType ar)
//Post operator:
RetType operator “重载运算符”(ArgType ar, int)
//Class operator
//Pre operator:
RetType operator “重载运算符”( )
//Post operator:
RetType operator “重载运算符”( int )
具体实例
class CPoint
{
private:
int m_nX;
int m_nY;
public:
CPoint(int x = 0, int y = 0) { m_nX = x; m_nY = y; }
CPoint operator ++ () // Pre decreament
{
m_nX += 1; m_nY += 1;
return CPoint(m_nX, m_nY);
}
CPoint operator -- (int) // Post decreament
{
CPoint p(*this);
m_nX -= 1; m_nY -= 1;
return CPoint(m_nX, m_nY);
}
};
int main(void)
{
CPoint cp(0, 0), cp1(1, 2), point;
point = ++cp;
point = cp1--;
return 1;
}
>>/<<运算符
重载模板
ostream& operator << (ostream& o, 类名& c)
{
//具体实现算法
return 0;
}
#include <iostream>
using namespace std;
class CComplex
{
private:
double m_dR, m_dI;
public:
CComplex(double r = 0, double i = 0)
{ m_dR = r; m_dI = i; }
friend ostream& operator << (ostream& o, CComplex& c);
};
ostream& operator << (ostream& o, CComplex& c)//只能是全局函数
{
o << c.m_dR << " + i" << c.m_dI;
return o;
}
int main()
{
CComplex a(1, 2);
cout << a << endl;
return 1;
}
20上机考试实操
#include <iostream>
using namespace std;
class Complex
{
private:
int real, image;
public:
Complex(int r = 0, int i = 0)
{
real = r;
image = i;
}
//输出重载
friend ostream& operator << (ostream& o, Complex& ox);
//+重载
friend Complex operator + (Complex& a, Complex& b);
//+=重载
friend Complex operator += (Complex& a, Complex& b);
};
ostream& operator << (ostream& o, Complex& ox)
{
if (ox.real == 0 && ox.image == 0)
{
cout << '0' << endl;
return o;
}
else
{
o << ox.real << '+' << ox.image << 'i' << endl;
return o;
}
}
Complex operator + (Complex& a, Complex& b)
{
Complex op;
op.real = a.real + b.real;
op.image = a.image + b.image;
return op;
}
Complex operator += (Complex& a, Complex& b)
{
a.real = a.real + b.real;
a.image = a.image + b.image;
return a;
}
int main()
{
Complex C1(1, 2), C2;
Complex C3 = C2;
cout << " C3 = " << C3 << endl;
C2 = C1 + C3;
cout << " C2 = " << C2 << endl;
C2 += C1;
cout << " C2 = " << C2 << endl;
}