题目描述
定义一个三维点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++; // 返回前加1
return 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--; // 返回前加1
return temp;
}
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;
}
这道题大家要注意符号的前后位置哦!