// Vector2D.h
#pragma once
#include <iostream>
using namespace std;
struct Vec2D
{
double m_vecX;
double m_vecY;
};
class Vector2D
{
public:
Vector2D(void);
Vector2D(const Vector2D &other);
Vector2D(double vecX, double vecY);
Vector2D(const Vec2D& vecVal);
virtual ~Vector2D(void);
public:
Vector2D& operator =(const Vector2D &other);
//Vector2D operator+(double vecX, double vecY);
Vector2D operator +(const Vector2D &other);
Vector2D operator -(const Vector2D &other);
Vector2D& operator ++(); //前自增
Vector2D operator ++(int); //后自增
// 转换运行符重载声明形式:operator 类型名();它没有返回类型,因为类型名就代表了它的返回类型,所以返回类型显得多余
// 一般来说,转换运算符与转换构造函数(即带一个参数的构造函数)是互逆的,如有了构造函数Test(int),那么最好有一个转换运算符int()。这样就不必提供对象参数重载运算符了
operator Vec2D() const;
//重载输入操作符
friend istream& operator >>(istream& instrm, Vector2D& vectorEle);
//重载输出操作符
friend ostream& operator <<(ostream& outstrm, const Vector2D& vectorEle);
protected:
double m_vecX;
double m_vecY;
};
// Vector2D.cpp
#include "Vector2D.h"
Vector2D::Vector2D(void)
{
m_vecX = 0.0;
m_vecY = 0.0;
}
Vector2D::Vector2D(double vecX, double vecY)
{
m_vecX = vecX;
m_vecY = vecY;
}
Vector2D::Vector2D(const Vector2D &other)
{
m_vecX = other.m_vecX;
m_vecY = other.m_vecY;
}
Vector2D::Vector2D(const Vec2D& vecVal)
{
this->m_vecX = vecVal.m_vecX;
this->m_vecY = vecVal.m_vecY;
}
Vector2D::~Vector2D(void)
{
}
Vector2D& Vector2D::operator=(const Vector2D &other)
{
this->m_vecX = other.m_vecX;
this->m_vecY = other.m_vecY;
return *this;
}
Vector2D Vector2D::operator+(const Vector2D &other)
{
Vector2D tmpVal;
tmpVal.m_vecX = this->m_vecX + other.m_vecX;
tmpVal.m_vecY = this->m_vecY + other.m_vecY;
return tmpVal;
}
Vector2D Vector2D::operator-(const Vector2D &other)
{
Vector2D tmpVal;
tmpVal.m_vecX = this->m_vecX - other.m_vecX;
tmpVal.m_vecY = this->m_vecY - other.m_vecY;
return tmpVal;
}
Vector2D& Vector2D::operator++()
{
this->m_vecX += 1;
this->m_vecY += 1;
return *this;
}
Vector2D Vector2D::operator++(int)
{
Vector2D tmpVal(*this);
this->m_vecX += 1;
this->m_vecY += 1;
return tmpVal;
}
Vector2D::operator Vec2D() const
{
Vec2D tmpVal;
tmpVal.m_vecX = this->m_vecX;
tmpVal.m_vecY = this->m_vecY;
return tmpVal;
}
istream& operator>>(istream& instrm, Vector2D& vectorEle)
{
cout<<"in operator>>\n";
cout<<"please input a vector X:";
instrm>>vectorEle.m_vecX;
cout<<"please input a vector Y:";
instrm>>vectorEle.m_vecY;
return instrm; //千万别忘了返回 in
}
ostream& operator<<(ostream& outstrm, const Vector2D& vectorEle)
{
outstrm<<"out operator<<\n";
outstrm<<vectorEle.m_vecX<<";"<<vectorEle.m_vecY<<endl;
return outstrm; //千万别忘了返回 out
}
//main.cpp
#include <cstdlib>
#include "Vector2D.h"
void OperatorTest()
{
Vector2D vectorVal1(1, 2), vectorVal2(1, 3);
Vec2D vecVal;
vecVal = vectorVal1;
Vector2D vectorVal3 = vectorVal1++;
vectorVal3 = ++vectorVal1;
vectorVal3 = vectorVal1 + vectorVal2;
cout<<vectorVal3<<" end"<<endl;
cin>>vectorVal3>>vectorVal1;
cout<<vectorVal3<<vectorVal1<<endl;
}
int main()
{
OperatorTest();
}