64,654
社区成员
发帖
与我相关
我的任务
分享
/*
* C plus plus learning.
* Question: How to overloading << for a class/object.
*/
#include <iostream>
using namespace std;
class Point {
private:
int x;
int y;
public:
Point();
Point( int x, int y );
~Point();
// FIXME: this overloading does not work
ostream &operator<<(ostream &output, const Point &thiz);
};
Point::Point() {}
Point::Point(int ax, int ay) {
x = ax;
y = ay;
}
Point::~Point() {}
ostream &Point::operator<<(ostream &output, const Point &thiz) {
cout << "(" << thiz.x << ", " << thiz.y << ")" << endl;
}
int main() {
Point a( 3, 4 );
cout << a;
return 0;
}
ostream &Point::operator<<(ostream &output, const Point &thiz);
把这个改成友元函数就OK friend ostream &operator<<(ostream &output, const Point &thiz);
ostream &operator<<(ostream &output, const Point &thiz)
{
output << "(" << thiz.x << ", " << thiz.y << ")" << endl;
return output;
}
/*
* C plus plus learning.
* Question: How to overloading << for a class/object.
*/
#include <iostream>
#include <cstdlib>
using namespace std;
class Point {
private:
int x;
int y;
public:
Point();
Point( int x, int y );
~Point();
// FIXME: this overloading does not work
friend ostream& operator<<(ostream &output, const Point &thiz);
};
Point::Point() {}
Point::Point(int ax, int ay) {
x = ax;
y = ay;
}
Point::~Point() {}
ostream& operator<<(ostream &output, const Point &thiz) {
output << "(" << thiz.x << ", " << thiz.y << ")";
return output;
}
int main() {
Point a( 3, 4 );
cout << a << endl;
system("PAUSE");
return 0;
}