#include using namespace std; template class Pair { // 使用友元函数模版的方式,可以避免重复声明 template friend ostream &operator<<(ostream &out, const Pair &p); private: T1 first; T2 second; public: Pair(T1 f, T2 s) : first(f), second(s) {} T1 getFirst() const { return first; } T2 getSecond() const { return second; } }; template ostream &operator<<(ostream &out, const Pair &p) { out << p.getFirst() << " " << p.getSecond(); return out; } int main() { Pair p1 = Pair("x", 20); Pair p2 = Pair("name", "disen"); // cout << p1 << endl; cout << p1 << "," << p2 << endl; return 0; }