运算符的重载

++/--运算符

++/- -  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;
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值