C++中的运算符重载问题

来源:互联网 发布:淘宝心是怎么升级的 编辑:程序博客网 时间:2024/06/03 21:32


//VPoint.h文件#pragma onceclass VPoint{public:VPoint(void);VPoint(int x,int y,int z);//运算符重载 //重载 + -friend VPoint operator + (const VPoint& pt1, const VPoint& pt2);friend VPoint operator - (const VPoint& pt1, const VPoint& pt2);//重载==  !=bool operator == (const VPoint& pt1 );bool operator != (const VPoint& pt1 );//重载输入输出friend std::ostream& operator << (std::ostream& os, const VPoint& pt);friend std::istream& operator >> (std::istream& is, const VPoint& pt);//+= -=VPoint& operator += (const VPoint& pt);VPoint& operator -= (const VPoint& pt);public:~VPoint(void);//成员变量private:int m_X;int m_Y;int m_Z;};

//VPoint.cpp文件#include <iostream>#include "VPoint.h"using namespace std;VPoint::VPoint(void){}VPoint::~VPoint(void){}VPoint::VPoint(int x,int y,int z){this->m_X = x;this->m_Y = y;this->m_Z = z;}//重载 + -VPoint operator + (const VPoint& pt1, const VPoint& pt2){VPoint pt(pt1);pt += pt2;return pt ;}VPoint operator - (const VPoint& pt1, const VPoint& pt2){VPoint pt(pt1);pt -= pt2;return pt;}//重载==  !=bool VPoint::operator == (const VPoint& pt1){return( this->m_X == pt1.m_X && this->m_Y == pt1.m_Y && this->m_Z == pt1.m_Z);}bool VPoint::operator != (const VPoint& pt1){return !(*this == pt1);}//重载输入输出std::ostream& operator << (std::ostream& os, const VPoint& pt){os << pt.m_X <<"\t" << pt.m_Y << "\t" <<pt.m_Z ;return os;}//+= -=VPoint& VPoint::operator += (const VPoint& pt){return VPoint( this->m_X += pt.m_X , this->m_Y += pt.m_Y , this->m_Z += pt.m_Z);}VPoint& VPoint::operator -= (const VPoint& pt){return VPoint( this->m_X -= pt.m_X , this->m_Y -= pt.m_Y , this->m_Z -= pt.m_Z);}

//operator.cpp文件#include <iostream>#include "VPoint.h"using namespace std;//立体坐标int main(){VPoint pt1(1,2,3);VPoint pt2(2,3,4);VPoint pt3(10,20,30);pt1 += pt2;cout<<pt1<<endl;cin.get();cin.get();return 0;}


0 0