C ++演習06(03)Point3D演算子のオーバーロード関数

トピック記述
プログラミング:3次元座標点を記述するクラスPoint3Dを定義し、「++」、「–」、「+」演算子をオーバーロードし、メンバー関数を使用してポスト++演算子とフレンド演算子を実装する必要があります。事前操作を実装し、追加演算子がオーバーロードされます。
メイン関数を記述し、Point3Dオブジェクトp1、p2(p1、p2の値はキーボードから入力されます)、p(デフォルト値を使用、デフォルト値は0,0,0)を定義し、
p = p1 ++を実行します; pの値を出力、p1
p = --p2; pの値を出力、p2
p = p1 + p2; pの値を出力
入力説明
2行
最初の3Dポイントの座標
2番目の3Dポイントの座標
出力の説明
次の操作を実行した後:
p = p1 ++; pの出力値、p1
p = --p2; pの出力値、p2
p = p1 + p2; pの出力値
入力例35
4
7 15
出力例
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