您的位置:首页 > 编程语言 > C语言/C++

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

2014-09-04 18:05 148 查看
//VPoint.h文件
#pragma once

class 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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息