C++兼容C结构:自定义转换操作符

#include <iostream>
using namespace std;
struct CPoint
{
    int x,y;
};

class Point
{
public:
	Point(int x, int y){
		pt.x = x;
		pt.y = y;
	}
	int x() const {return pt.x;}
	int y() const {return pt.y;}
	CPoint get_pt() {
		return pt;
	}
	// 自定义转换操作符
	operator CPoint(){
		return pt;
	}
	operator int(){
		return pt.x + pt.y;
	}
	friend ostream& operator << (ostream &,Point & ) ;
private:
	CPoint pt;
};
ostream& operator << (ostream & os, Point & point)
{
	//	os<< "(x="<<point.x() <<",y="<<point.y()<<")" <<flush;
	os<< "[x="<<point.pt.x <<",y="<<point.pt.y<<"]" <<flush;
	return os;
}
int main()
{
	Point p(1,2);
	cout<<p<<endl;
	//	CPoint cp = CPoint(p);
	// or
	CPoint cp = (CPoint)p;
	cout<<"addr:"<<hex<<&cp<<dec<<":"<<cp.x<<endl;
	cout<<"addr:"<<hex<<&(p.get_pt())<<dec<<":"<<p.x()<<endl;

	cout<<"int val:"<<int(p)<<endl;
    return 0;
}

  

posted @ 2012-12-11 17:54  庚武  Views(267)  Comments(0)    收藏  举报