将现在的操作符与一个成员函数相关联并将该操作与其类的对象(作为它的操作数)一起使用,称为操作符重载。重载运算符用operator关键字来完成。
操作符函数的格式如下:
operator op(argument-list)
其中,op是将要重载的操作符,例如,operator+()重载+操作符。operator *()重载*操作符。op必须是有效的C++操作符,不能虚构一个新的符号。
#include <iostream>
class CPoint
{
private:
int nPointX,nPointY;
public:
CPoint(int _nX=0,int _nY=0)
{
nPointX=_nX;
nPointY=_nY;
}
void SetPoint(int _nX,int _nY)
{
nPointX=_nX;
nPointY=_nY;
}
int GetPointX() {return nPointX;}
int GetPointY() {return nPointY;}
CPoint operator+(CPoint &_obj)
{
int nX=nPointX+_obj.GetPointX();
int nY=nPointY+_obj.GetPointY();
return CPoint(nX,nY);
}
void Show()
{
std::cout<<"nPointX:"<<nPointX<<std::endl;
std::cout<<"nPointY:"<<nPointY<<std::endl;
}
};
int main(int argc, const char * argv[])
{
// insert code here...
CPoint pointA(10,20);
CPoint pointB(20,20);
CPoint pointC;
pointC=pointA+pointB;
pointC.Show();
return 0;
}
#include <iostream>
class CPoint
{
private:
int m_nPointX,m_nPointY;
public:
CPoint(int _nX=0,int _nY=0)
{
m_nPointX=_nX;
m_nPointY=_nY;
}
void SetPoint(int _nX,int _nY)
{
m_nPointX=_nX;
m_nPointY=_nY;
}
void Show()
{
std::cout<<"m_nPointX="<<m_nPointX<<std::endl;
std::cout<<"m_nPointY="<<m_nPointY<<std::endl;
}
};
std::ostream& operator<<(std::ostream& _out,CPoint& _obj)
{
std::cout<<"In operator << ()"<<std::endl;
_obj.Show();
return _out;
}
std::istream& operator>>(std::istream& _in,CPoint& _obj)
{
int nX,nY;
nX=nY=0;
std::cout<<"Please input point X:";
_in>>nX;
std::cout<<"Please input point Y:";
_in>>nY;
_obj.SetPoint(nX,nY);
return _in;
}
int main(int argc, const char * argv[])
{
// insert code here...
CPoint pointA(10,20);
CPoint pointB(20,20);
CPoint pointC;
std::cout<<"Point pointA:"<<std::endl;
std::cout<<pointA;
std::cout<<"Point pointB:"<<std::endl;
std::cout<<pointB;
std::cout<<"Input pointC:"<<std::endl;
std::cin>>pointC;
std::cout<<pointC;
return 0;
}
#include <iostream>
class Clock
{
private:
int Hour,Minute,Second;
public:
Clock(int _h=0,int _m=0,int _s=0)
{
Hour=_h;
Minute=_m;
Second=_s;
}
void ShowTime()const;
void operator ++();
void operator ++(int);
};
void Clock::operator++()
{
Second++;
if(Second>=60)
{
Second-=60;
Minute++;
if (Minute>=60)
{
Minute-=60;
Hour++;
Hour%=24;
}
}
std::cout<<"++Clock:";
}
void Clock::operator++(int)
{
Second+=1;
if(Second>=60)
{
Second-=60;
Minute++;
if (Minute>=60)
{
Minute-=60;
Hour++;
Hour%=24;
}
}
std::cout<<"Clock++:";
}
void Clock::ShowTime()const
{
std::cout<<Hour<<":"<<Minute<<":"<<Second<<std::endl;
}
int main(int argc, const char * argv[])
{
// insert code here...
Clock myClock(23,59,59);
std::cout<<"First time output:";
myClock.ShowTime();
myClock++;
myClock.ShowTime();
++myClock;
myClock.ShowTime();
return 0;
}