題目描述
定義一個三維點Point類,利用友元函數重載"++"和"--"運算符,并區分這兩種運算符的前置和后置運算。
++表示x\y\z坐標都+1,--表示x\y\z坐標都-1
請完成以下程序填空
輸入
只有一行輸入,輸入三個整數,表示點的x/y/z坐標
輸出
由主函數自行輸出
//
輸入樣例:
10 20 30
輸出樣例:
x=11 y=21 z=31
x=10 y=20 z=30
x=11 y=21 z=31
x=11 y=21 z=31
x=9 y=19 z=29
x=10 y=20 z=30
x=9 y=19 z=29
x=9 y=19 z=29
代碼原先框架:
#include <iostream>
using namespace std;
class Point;
Point operator -- (Point & );
Point operator -- (Point &, int);
class Point {
private:
?? ?int x, y, z;
public:
?? ?Point(int tx=0, int ty=0, int tz=0 )
?? ?{?? ?x = tx, y = ty, z = tz;?? ?}
?? ?Point operator ++ ();
?? ?Point operator ++ (int);
?? ?friend Point operator -- (Point & );
?? ?friend Point operator -- (Point &, int);
?? ?void print();
};
//完成以下填空
/********** Write your code here! **********/
/*******************************************/
//完成以上填空
int main()
{?? ?int tx, ty, tz;
?? ?cin>>tx>>ty>>tz;
?? ?Point p0(tx, ty, tz); //原值保存在p0
?? ?Point p1, p2;?? ?//臨時賦值進行增量運算
?? ?//第1行輸出
?? ?p1 = p0;
?? ?p1++;;
?? ?p1.print();
?? ?//第2行輸出
?? ?p1 = p0;
?? ?p2 = p1++;
?? ?p2.print();
?? ?//第3、4行輸出,前置++
?? ?p1 = p0;
?? ?(++p1).print();
?? ?p1.print();
?? ?//第5、6行輸出,后置--
?? ?p1 = p0;
?? ?p1--;
?? ?p1.print();
?? ?p0.print();
?? ?//第7、8行輸出,前置--
?? ?p1 = p0;
?? ?(--p1).print();
?? ?p1.print();
?? ?return 0;
}
AC代碼:
#include <iostream>
using namespace std;class Point;
Point operator--(Point &);
Point operator--(Point &, int);class Point
{
private:int x, y, z;public:Point(int tx = 0, int ty = 0, int tz = 0){x = tx, y = ty, z = tz;}Point operator++();Point operator++(int);friend Point operator--(Point &);friend Point operator--(Point &, int);void print();
};
// 完成以下填空
Point Point::operator++(int)
{Point temp(*this); // 返回原來的值,先做原對象備份x++;y++;z++; // 返回前加1return temp; // 返回備份值,即加1前的值
}
Point Point::operator++()
{x++;y++;z++; // 先增量return *this; // 再返回原對象
}
void Point::print()
{cout << "x=" << x << " " << "y=" << y << " " << "z=" << z << endl;
}
Point operator--(Point &a)
{a.x--;a.y--;a.z--; // 先增量return a; // 再返回原對象
}
Point operator--(Point &a, int)
{Point temp(a); // 返回原來的值,先做原對象備份a.x--;a.y--;a.z--; // 返回前加1return temp;
}int main()
{int tx, ty, tz;cin >> tx >> ty >> tz;Point p0(tx, ty, tz); // 原值保存在p0Point p1, p2; // 臨時賦值進行增量運算// 第1行輸出p1 = p0;p1++;;p1.print();// 第2行輸出p1 = p0;p2 = p1++;p2.print();// 第3、4行輸出,前置++p1 = p0;(++p1).print();p1.print();// 第5、6行輸出,后置--p1 = p0;p1--;p1.print();p0.print();// 第7、8行輸出,前置--p1 = p0;(--p1).print();p1.print();return 0;
}
這道題大家要注意符號的前后位置哦!