C++习题06(03)Point3D运算符重载函数

题目描述
编程:定义描述三维坐标点的类Point3D,重载”++”、”–”、”+”运算符,要求用成员函数实现后置++运算符,用友元运算符实现前置–运算和加法运算符重载。
编写主函数,定义Point3D类对象p1、p2(p1、p2的值均从键盘输入)、p(使用默认值,默认值为0,0,0),执行
p = p1++; 输出p、p1的值
p = --p2; 输出p、p2的值
p = p1 + p2; 输出p的值
输入描述
两行
第一个三维点的坐标
第二个三维点的坐标
输出描述
执行以下操作后:
p = p1++; 输出p、p1的值
p = --p2; 输出p、p2的值
p = p1 + p2; 输出p的值
输入样例
3 5 4
7 1 5
输出样例
p1=(4,6,5)
p=(3,5,4)
p2=(6,0,4)
p=(6,0,4)
p=(10,6,9)

#include <iostream>

using namespace std;


class Point3D
{
    
    
public:
	Point3D(int a, int b, int c);
	Point3D operator++(int);
	friend Point3D operator--(Point3D &op);
	friend Point3D operator+(Point3D &op1, Point3D &op2);
	void print();
private:
	int x, y, z;
};
Point3D::Point3D(int a, int b, int c)
{
    
    
	x = a;
	y = b;
	z = c;
}
Point3D Point3D ::operator++(int)
{
    
    
	Point3D t(*this);
	x++;
	y++;
	z++;
	return t;
}
Point3D operator--(Point3D &op)
{
    
    
	--op.x;
	--op.y;
	--op.z;
	return op;
}
Point3D operator+(Point3D &op1, Point3D &op2)
{
    
    
	Point3D t(0,0,0);
	t.x = op1.x + op2.x;
	t.y = op1.y + op2.y;
	t.z = op1.z + op2.z;
	return t;
}
void Point3D::print()
{
    
    
	cout << "(" << x << "," << y << "," << z << ")" << endl;
}
int main()
{
    
    
	Point3D p(0,0,0);
	int x1, x2, y1, y2,z1,z2;
	cin >> x1 >> y1 >> z1 >> x2 >> y2 >> z2;
	Point3D p1(x1, y1, z1);
	Point3D p2(x2, y2, z2);
	p = p1++;
	cout << "p1=";
	p1.print();
	cout << "p=";
	p.print();
	p = --p2;
	cout << "p2=";
	p2.print();
	cout << "p=";
	p.print();

	p = p1 + p2;
	cout << "p=";
	p.print();
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_44179485/article/details/105452222