zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    项目工作总结 (转)
    mysql-笔记 操作语句
    QTP自动化测试-excel sheet页数量过多--但是不能在qtp里被识别
    mysql-笔记 定义语句
    HDU
    CodeForces
    CodeForces
    CodeForces
    CodeForces
    CodeForces
  • 原文地址:https://www.cnblogs.com/xiximayou/p/12108077.html
Copyright © 2011-2022 走看看