• 模板与友元


    概述

    类模板可以有友元,函数模板可以声明为类的友元。友元与模板分为以下几种情况:
    模板与普通的类、函数之间:

    • 函数、类、类的成员函数作为类模板的友元
    • 函数模板作为类的友元

    模板与模板之间

    • 类模板作为类模板的友元
    • 函数模板作为类模板的友元

    1、函数、类、类的成员函数作为类模板的友

    void Func1() { }
    class A { };
    class B
    {
    public:
    	void Func() { }
    };
    template <class T>
    class Tmpl
    {
    	friend void Func1();
    	friend class A;
    	friend void B::Func();
    }; 
    

    注意:任何从Tmp1实例化来的类, 都有以上三个友元。

    4、函数模板作为类的友元

    //函数模板作为类模板的友元
    template<class T1,class T2>
    bool Pair<T1,T2>::operator < ( const Pair<T1,T2> & p) const
    { //"小"的意思就是关键字小
    return key < p.key;
    }
    template <class T1,class T2>
    ostream & operator<< (ostream & o,const Pair<T1,T2> & p)
    {
    o << "(" << p.key << "," << p.value << ")" ;
    return o;
    }
    
    int main()
    {
    Pair<string,int> student("Tom",29);
    Pair<int,double> obj(12,3.14);
    cout << student << " " << obj;
    return 0;
    }
    输出:
    (Tom,29) (12,3.14)
    

    注意:任意从 template <class T1,class T2>ostream & operator<< (ostream & o,const Pair<T1,T2> & p)生成的函数,都是任意Pair摸板类的友元。

    3、函数模板作为类模板的友元

    #include <iostream>
    #include <string>
    using namespace std;
    template <class T1,class T2>
    class Pair
    {
    private:
    	T1 key; //关键字
    	T2 value; //值
    public:
    	Pair(T1 k,T2 v):key(k),value(v) { };
    	bool operator < ( const Pair<T1,T2> & p) const;
    	template <class T3,class T4>
    	friend ostream & operator<< ( ostream & o,
    	const Pair<T3,T4> & p);
    };
    

    4、类模板作为类模板的友元

    #include <iostream>
    using namespace std;
    class A
    {
    int v;
    public:
    A(int n):v(n) { }
    template <class T>
    friend void Print(const T & p);
    };
    template <class T>
    void Print(const T & p)
    {
    cout << p.v;
    }
    int main() {
    A a(4);
    Print(a);
    return 0;
    }
    输出:
    4
    

    注意:所有从 template <class T>void Print(const T & p)生成的函数,都成为 A 的友元但是自己写的函数void Print(int a) { }不会成为A的友元。

  • 相关阅读:
    C++ map详解
    C++ vector和list的区别
    C++静态存储,动态存储
    C++文件输入和输出
    C/C++数组名与指针的区别详解
    C++运算符重载详解
    poj3177Redundant Paths tarjan缩点
    C++编译过程与内存空间
    [JAVA &#183; 0基础]:19.容器类
    FFmpeg总结(六)AV系列结构体之AVPacket
  • 原文地址:https://www.cnblogs.com/lasnitch/p/12764229.html
Copyright © 2020-2023  润新知