在模板类中输入运算符>>和输出运算符<<的重载,使用友元在类内声明,在类外实现。
#include <iostream>
using namespace std;
template<typename T>
class Test {
public:
Test(const T& t) :data(t) {}
//输入流重载声明
template<typename U>
friend inline istream& operator>>(istream& in, Test<U>& t);
//输出流重载声明
template<typename U>
friend inline ostream& operator<<(ostream& out, const Test<U>& t);
private:
T data;
};
//输入流重载实现
template<typename U>
inline istream& operator>>(istream& in, Test<U>& t) {
return in >> t.data;
}
//输出流重载实现
template<typename U>
inline ostream& operator<<(ostream& out, const Test<U>& t) {
return out << "data is " << t.data;
}
int main() {
Test<int> b(3);
cout << b << '\n';
cin >> b;
cout << b << '\n';
return 0;
}