64,637
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
using namespace std;
template <class T1, class T2>
class Test {
public:
Test(T1 xx = T1(0), T2 yy = T2(0));
Test<T1, T2>& operator = (Test<T1, T2>& t);
Test<T1, T2> operator + (Test<T1, T2>& t);
Test<T1, T2> operator - (Test<T1, T2>& t);
T1 get_x() {return x; }
T2 get_y() {return y; }
private:
T1 x;
T2 y;
};
template <class T1, class T2>
Test<T1, T2>::Test(T1 xx, T2 yy)
: x(xx)
, y(yy)
{
}
template <class T1, class T2>
Test<T1, T2>& Test<T1, T2>::operator = (Test<T1, T2>& t)
{
x = t.x;
y = t.y;
}
template <class T1, class T2>
Test<T1, T2> Test<T1, T2>::operator + (Test<T1, T2>& t)
{
Test<T1, T2> tmp;
tmp.x = x + t.x;
tmp.y = y + t.y;
return tmp;
}
template <class T1, class T2>
Test<T1, T2> Test<T1, T2>::operator - (Test<T1, T2>& t)
{
Test<T1, T2> tmp;
tmp.x = x - t.x;
tmp.y = y - t.y;
return tmp;
}
class Bridge : public ostream {
public:
enum Type {op1, op2};
Bridge(ostream& _os, Type _type) : os(_os), type(_type) {}
template <class T1, class T2>
ostream& operator<< (Test<T1, T2>& t);
private:
ostream& os;
Type type;
};
template <class T1, class T2>
ostream& operator<< (ostream& os, Test<T1, T2>& t)
{
Bridge* pB = 0;
if ((pB = dynamic_cast<Bridge*>(&os)) != 0) {
*pB <<t;
delete pB;
return os;
}
os <<"t.x == " <<t.get_x() <<endl;
os <<"t.y == " <<t.get_y() <<endl;
return os;
}
template <class T1, class T2>
ostream& Bridge::operator<< (Test<T1, T2>& t)
{
if (type == Bridge::op1) {
os <<"op1.. x == " <<t.get_x() <<endl;
} else if (type == Bridge::op2) {
os <<"op2.. y == " <<t.get_y() <<endl;
}
return os;
}
ostream& op1(ostream& os)
{
Bridge* pB = new Bridge(os, Bridge::op1);
return *pB;
}
ostream& op2(ostream& os)
{
Bridge* pB = new Bridge(os, Bridge::op2);
return *pB;
}
int main()
{
Test<int, int> t1(11, 22);
Test<int, int> t2(11, 22);
Test<int, int> t(0, 0);
cout <<t1;
cout <<t2;
t = t1 + t2;
cout <<op1 <<t;
cout <<op2 <<t;
}
int main()
{
Test<int, int> t1(11, 22);
Test<int, int> t2(11, 22);
// Test<int, int> t(0, 0);
cout <<t1;
cout <<t2;
Test<int, int> t = t1 + t2;//代码中operator= 忘了没有写返回值
cout <<op1 <<t;
cout <<op2 <<t;
}