linux中模板类使用友元函数

本文详细解析了在Linux环境下,如何正确地在模板类中使用友元函数,包括内部声明与外部声明的注意事项,以及重载函数的处理方式。

linux中模板类使用友元函数时注意:

1. 在linux下不仅要在类里面声明函数,注意类中友元函数前不要定义模板类,直接在函数名后面加<T(友元函数类名称)>

friend ostream& operator<< <T>(ostream& os, test1<T>& t);

2. 在类外面也需要声明友元函数(包括重载函数),并且前面需要定义模板类

 

#pragma once
#include <iostream>
using namespace std;
template<class T> class test1;
template<class T> ostream& operator<<(ostream& os, test1<T>& t);
template<class T>
class test1{
    public:
        
        friend ostream& operator<< <T>(ostream& os, test1<T>& t);
        test1(T age);
        void Show();
    public:
        
        static int a;
        T age;
};

 

#include <iostream> using namespace std; //在类外进行前置声明 // 友元函数在类外面实现,并且都在同一个CPP文件中, //需要在前面对类和对应操作符重载函数进行前置声明。 // 同时在类内部声明的对应函数需要在参数链表前加入 "<T>"。 template <class T1, class T2> class Person; template <class T1, class T2> std::ostream& operator<<(std::ostream& os, Person<T1, T2>& p); //类模板 类外实现 //类模板 template <class T1, class T2> class Person { public: //模板类使用友元 //重载左移操作符,用于直接打印输出 //方法1 //template <class T1, class T2> //定要加 这句,不过这样的写法在linux不能通过 //friend std::ostream& operator<<(std::ostream& os, Person<T1, T2>& p); //方法2在操作符后加 <T1,T2>,同时进行类前置声明 //方法1 在VS中可以便宜,但 要在Linux下会出错 friend std::ostream& operator<<<T1,T2>(std::ostream& os, Person<T1, T2>& p); Person(T1 id, T2 age); void showPerson(); private: T1 mId_; T2 mAge_; }; //声明和实现分开时,我们需要对函数的声明做特殊处理, //注意,这里类名应是Person<T1,T2> template <class T1, class T2> Person<T1, T2>::Person(T1 id, T2 age) { this->mAge_ = age; this->mId_ = id; } template <class T1, class T2> void Person<T1, T2>::showPerson() { std::cout << "id.....:" << mId_ << ",age:" << mAge_ << std::endl; } //通过重载左移操作符,用于直接打印输出 template <class T1, class T2> std::ostream& operator<<(std::ostream& os, Person<T1, T2>& p) { std::cout << "operator--- id: " << p.mId_ << ",age:" << p.mAge_ << std::endl; return os; } //类模板在类外实现时,不要滥用友元 void testShow() { //函数模板在调用时,可以自动进行类型推导 //类模板必须显式声明 Person<int, int> person(12, 11111); //person.showPerson(); std::cout << "ddd: " << person << std::endl; } int main() { testShow(); return 0; }
06-11
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值