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

类模板外部实现

#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");
}

结果显示

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值