类模板外部实现(类模板重载操作符和友元的使用 笔记)

类模板外部实现

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
template<class T>
class Person
{
    //重载左移操作符
    template<class T>//一定要加 在linux 不能通过  要在Linux下编译通过 需要friend ostream& operator<<<T>(ostream& os, Person<T>& p);
    friend ostream& operator<<(ostream& os, Person<T>& p);
public:
    Person(T age ,T id);
    void show();

public:
    T age;
    T id;
private:

};
template<class T>
Person<T>::Person(T age, T id)
{
    this->age = age;
    this->id = id;
}
template<class T>
void Person<T>::show()
{
    cout << "Age:" << age <<endl<< "Id:" << id << endl;
}
template<class T>
ostream& operator<<(ostream& os, Person<T>& p)
{
    os << "Age:" << p.age << endl << "Id:" << p.id << endl;
    return os;
}
int main()
{
    Person<int> p(10, 20);
    //p.show();
    cout << p;
    system("pause");
}

结果显示

猜你喜欢

转载自blog.csdn.net/qq_23859701/article/details/81411486
今日推荐