大佬们帮忙看看。重载了<<和自增运算符,用来输出自己定义的Point类,前缀++正常输出,后缀++报错:
没有与这些操作数匹配的"<<"运算符,操作类型为ostream<<Point。但是p++的返回值就是Point啊?
代码如下:
//通过重载实现点类的自增自减和输出
#include <iostream>
using namespace std;
class Point
{
int _x, _y;
public:
Point(int x, int y) :_x(x), _y(y) {}
Point& operator ++();//前置++不需要参数
Point operator ++(int);//后置++需要参数来作为标志
Point& operator --();
Point operator --(int);
friend ostream& operator << (ostream& o, Point& p);
};
Point& Point:: operator ++ ()
{
_x++;
_y++;
return *this;
}
/* ++i在c++的定义最后返回的是对象的引用*/
Point Point::operator ++ (int)
{
Point temp = *this;
++* this;
return temp;
}
/* i++在c++的定义中返回的是对象的值
后缀操作符接受一个额外的int型作为形参,并不使用该形参仅做区分*/
Point& Point::operator --()
{
_x--;
_y--;
return *this;
}
Point Point::operator --(int)
{
Point temp = *this;
++* this;//复用了前缀++的重载
return temp;
}
ostream& operator << (ostream& o, Point& p)
{
o << "(" << p._x << "," << p._y << ")" << endl;
return o;
}
int main()
{
Point p(1, 2);
cout << p << endl;
//cout << p++ << endl;//重载的后缀++和--都不能被<<识别
cout << ++p << endl;
//cout << p-- << endl;//
cout << --p << endl;
return 0;
}