重载输入、输出操作符。
#include <iostream> using namespace std; class Point { private: int x; int y; public: Point() { }; friend ostream &operator<< (ostream &os,const Point &p){ os<<p.x<<","<<p.y; return os; } friend istream &operator>> (istream &is,Point &p){ is>>p.x>>p.y; return is; } }; int main() { Point p; while(cin >> p) { cout << p << endl; } return 0; }第二个例子。
// 输入/输出运算符重载 #include<iostream> using namespace std; class Site{ public: Site(){ x=0; y=0; } Site(int a, int b){ x = a; y = b; } friend ostream &operator<< (ostream &os,const Site &s); friend istream &operator>> (istream &is, Site &s);// 修改内容所以不用 const private: int x,y; }; ostream &operator<< (ostream &os,const Site &s){ os<<"X: "<<s.x<<" "<<"Y: "<<s.y<<endl; return os; } istream &operator>> (istream &is, Site &s){ is>>s.x>>s.y; return is; } int main(){ Site D1(3,4),D2; cout<<"Test:"<<endl; cin>>D2; cout<<D1<<D2; return 0; }