/******************************************** xqueue_print ostream & operator<< (ostream & os, const xpoint & x) int a; int &ra=a; //定义引用ra,它是变量a的引用,即别名 friend xpoint operator +(const xpoint & x1, const xpoint & x2); friend ostream& operator <<(ostream & os, const xpoint & x); 重载 << cout template <class T> ##Stack<T>& operator =(const Stack<T>& rightSide); ********************************************/ #include <iostream> using namespace std; template <class T> class xqueue{ public: xqueue(); void enqueue(T item); void sort(T *num, int len); void print()const; xqueue<T>& operator<<(const T & x){ data[tail] = x; tail = (tail + 1) % 10; return *this; } xqueue<T>& operator>>(T & x){ head = (head + x)%10; return *this; } private: T data[10]; int head; int tail; }; template <class T> xqueue<T>::xqueue():head(0),tail(0){} template <class T> void xqueue<T>::enqueue(T item){ data[tail] = item; tail = (tail +1)%10; } template <class T> void xqueue<T>::print()const{ for(int i = head; i != tail; i=(i+1)%10){ cout << data[i] << endl; } } class RN{ public: RN(int _x, int _y); bool operator>(RN rn)const; friend ostream & operator<< (ostream & os, const RN & x); void print()const; private: int x; int y; //x/y }; RN::RN(int _x = 1, int _y = 1){ x = _x; y = _y; } bool RN::operator>(RN rn)const{ return x/(double)y > rn.x/(double)rn.y; } ostream & operator<< (ostream & os, const RN & x){ os << x.x << "/" << x.y; return os; } class xpoint{ public: xpoint(int _x, int _y); bool operator >(xpoint xp)const; friend ostream & operator <<(ostream & os, const xpoint & x); void print()const; private: int x, y; }; xpoint::xpoint(int _x = 0, int _y = 0){ x = _x; y = _y; } bool xpoint::operator >(xpoint xp)const{ return (x*x + y*y) > (xp.x*xp.x + xp.y*xp.y); } ostream & operator <<(ostream & os, const xpoint & x){ os << x.x << "," << x.y; return os; } template <class T> void print_array(T *buf, int len) { T tmp; for(int i = 0; i < len; i++){ buf[i].print(); } } template <class T> void xqueue<T>::sort(T *num, int len) { int i, j; T tmp; for(i = 0; i < len; i++){ for(j = 0; j < len - i - 1; j++){ if(num[j] > num[j + 1]){ //注意是num[j] and num[j + 1] tmp = num[j + 1]; num[j + 1] = num[j]; num[j] = tmp; } } } } int main(){ xqueue<RN> q1; q1.enqueue(RN(1,2)); q1.enqueue(RN(4,2)); q1.enqueue(RN(5,2)); q1.print(); xqueue<xpoint> q2; q2.enqueue(xpoint(1,8)); q2.enqueue(xpoint(5,8)); q2.print(); xqueue<int> q3; q3<<5<<6<<8; q3.print(); } /*$ ./a.out 1/2 4/2 5/2 1,8 5,8 5 6 8 */