c++类的一点操作 (运算符重载求两个点的一些问题)完成这些算是c++入门了


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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值