1.main函数
#include <iostream>
#include "Point2F.h"
using namespace std;
int main()
{
int count;
float zoom, p1x,p1y, p2x, p2y;
cout << "请输入两向量的坐标(p1,p2):" << endl;
while (cin >> p1x >> p1y>>p2x>>p2y)
{
Point2F p1(p1x, p1y), p2(p2x, p2y);
cout << "输入序号1.加2.减3.点乘4.求模5.缩放:" << endl;
cin >> count;
switch (count)
{
case 1:p1 + p2; cout << p1<<endl; break;
case 2:p1 -= p2; cout << p1<<endl; break;
case 3:cout << p1*p2<< endl; break;
case 4:cout <<mod(p1,p2)<< endl; break;
case 5:cout << "缩放倍数是:" << endl; cin >> zoom; Zoom(p1, zoom); Zoom(p2, zoom);
cout << p1 << p2;
default:cout << "若要继续,输入两向量的坐标,否则EOF退出" << endl;
break;
}
}
system("pause");
return 0;
}
2.头文件
#pragma once
#include <iostream>
using namespace std;
class Point2F
{
public: //构造函数
Point2F() = default;
Point2F(float X,float Y,float Zoom):x(X),y(Y),zoom(Zoom){}
Point2F(float X, float Y):x(X), y(Y){}
public: //实现函数
Point2F & operator + (const Point2F &p1 );
Point2F &operator-=(const Point2F&p1);
float operator*(const Point2F&p1);
friend void Zoom(Point2F &p1, float zoom);
friend float mod(const Point2F&p1, const Point2F&p2);
friend istream&operator>>(istream&is, Point2F p1);//友元函数
friend ostream&operator<<(ostream&os, Point2F p1);
private:
float x = 0, y = 0;
float zoom = 1;
};
3.cpp
#include "Point2F.h"
#include <cmath>
#include <iostream>
Point2F & Point2F::operator+(const Point2F & p1)
{
x = x + p1.x;
y = y + p1.x;
return *this;
}
Point2F&Point2F::operator-=(const Point2F&p1)
{
x = x - p1.x;
y = y - p1.y;
return *this;
}
float Point2F::operator*(const Point2F & p1)
{
float multiplicate = x * p1.x + y * p1.y;
return multiplicate;
}
float mod(const Point2F & p1, const Point2F & p2)
{
float Mod = sqrt((p1.x - p2.x)*(p1.x - p2.x) + (p1.y - p2.y)*(p1.y - p2.y));
return Mod;
}
void Zoom(Point2F &p1,float zoom)
{
p1.x *= zoom; p1.y *= zoom;
}
istream & operator>>(istream & is, Point2F p1)
{
is >> p1.x >> p1.y;
return is;
}
ostream & operator<<(ostream & os, Point2F p1)
{
os << "(" << p1.x << "," << p1.y << ")";
return os;
}