c++问题:定义一个平面直角坐标系上的一个点的类CPoint

2024-12-03 03:45:11
推荐回答(2个)
回答1:

#include
#include
using namespace std;

class CPoint;
istream &operator >> (istream &in, CPoint &p);
ostream &operator << (ostream &out, const CPoint &p);

class CPoint
{
public:
CPoint(int _x = 0, int _y = 0) : x(_x), y(_y) {}
CPoint(CPoint &rhs) : x(rhs.x), y(rhs.y) {}
int GetX() { return x; }
int GetY() { return y; }
friend istream &operator >> (istream &in, CPoint &p);
friend ostream &operator << (ostream &out, const CPoint &p);
CPoint operator++(int) // 后缀++
{
CPoint temp(x, y);
x++, y++;
return temp;
}
CPoint &operator++() // 前缀++
{
++x, ++y;
return *this;
}

CPoint operator--(int) // 后缀--
{
CPoint temp(x, y);
x--, y--;
return temp;
}
CPoint operator--() // 前缀--
{
--x, --y;
return *this;
}
private:
int x, y;
};

istream &operator >> (istream &in, CPoint &p)
{
in >> p.x >> p.y;
return in;
}

ostream &operator << (ostream &out, const CPoint &p)
{
out << p.x << ' ' << p.y;
return out;
}

void main()
{
CPoint pt(15, 12);
cout << pt++ << endl;
cout << pt << endl;
cout << ++pt << endl;

cout << pt-- << endl;
cout << pt << endl;
cout << --pt << endl;
}

回答2:

#include

#include

using
namespace
std;
class
CPoint;
istream
&operator
>>
(istream
&in,
CPoint
&p);
ostream
&operator
<<
(ostream
&out,
const
CPoint
&p);
class
CPoint
{
public:
CPoint(int
_x
=
0,
int
_y
=
0)
:
x(_x),
y(_y)
{}
CPoint(CPoint
&rhs)
:
x(rhs.x),
y(rhs.y)
{}
int
GetX()
{
return
x;
}
int
GetY()
{
return
y;
}
friend
istream
&operator
>>
(istream
&in,
CPoint
&p);
friend
ostream
&operator
<<
(ostream
&out,
const
CPoint
&p);
CPoint
operator++(int)
//
后缀++
{
CPoint
temp(x,
y);
x++,
y++;
return
temp;
}
CPoint
&operator++()
//
前缀++
{
++x,
++y;
return
*this;
}
CPoint
operator--(int)
//
后缀--
{
CPoint
temp(x,
y);
x--,
y--;
return
temp;
}
CPoint
operator--()
//
前缀--
{
--x,
--y;
return
*this;
}
private:
int
x,
y;
};
istream
&operator
>>
(istream
&in,
CPoint
&p)
{
in
>>
p.x
>>
p.y;
return
in;
}
ostream
&operator
<<
(ostream
&out,
const
CPoint
&p)
{
out
<<
p.x
<<
'
'
<<
p.y;
return
out;
}
void
main()
{
CPoint
pt(15,
12);
cout
<<
pt++
<<
endl;
cout
<<
pt
<<
endl;
cout
<<
++pt
<<
endl;
cout
<<
pt--
<<
endl;
cout
<<
pt
<<
endl;
cout
<<
--pt
<<
endl;
}