c++之类模板和友元

时间:2022-07-23
本文章向大家介绍c++之类模板和友元,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

全局函数类内实现:直接在类内声明友元即可;(建议使用这种,更简单)

全局函数类外实现:需要提前让编译器知道全局函数的存在;

#include<iostream>
using namespace std;

//通过类外实现需要先知道Person;
template<class T1, class T2>
class Person;

//通过类外实现需要先知道show2();
template<class T1, class T2>
void show2(Person<T1, T2> p) {
    cout << "姓名:" << p.name << endl;
    cout << "年龄:" << p.age << endl;
};

template<class T1, class T2>
class Person {
    //全局函数类内实现
    //说明:这里这个函数已经不是类的成员函数了,在调用时直接使用即可,而不用p.show();
    friend void show(Person<T1, T2> p) {
        cout << "姓名:" << p.name << endl;
        cout << "年龄:" << p.age << endl;
    }
    //全局函数类外实现
    //加空模板参数列表
    //需要让编译器提前知道这一个函数的存在
    friend void show2<>(Person<T1, T2> p);
public:
    Person(T1 name, T2 age) {
        this->name = name;
        this->age = age;
    }
private:
    T1 name;
    T2 age;
};

void test() {
    Person<string, int> p("tom", 12);
    show(p);
    show2(p);
}

int main() {
    test();
    system("pause");
    return 0;
}