全局函数类内实现:直接在类内声明友元即可;(建议使用这种,更简单)
全局函数类外实现:需要提前让编译器知道全局函数的存在;
#include<iostream>using namespace std;//通过类外实现需要先知道Person;template<class T1,class T2>class Person;通过类外实现需要先知道show2();template<voID show2(Person<T1,T2> p) { cout << "姓名:" << p.name << endl; cout << 年龄:" << p.age << endl;};template< Person { 全局函数类内实现 说明:这里这个函数已经不是类的成员函数了,在调用时直接使用即可,而不用p.show(); frIEnd voID show(Person<T1,1)"> p) { cout << endl; cout << endl; } 全局函数类外实现 加空模板参数列表 需要让编译器提前知道这一个函数的存在 frIEnd voID show2<>(Person<T1,1)"> p);public: Person(T1 name,T2 age) { this->name = name; this->age = age; }private: T1 name; T2 age;};voID test() { Person<string,1)">int> p(tom",12); show(p); show2(p);}int main() { test(); system(pause"); return 0;}总结
以上是内存溢出为你收集整理的c++之类模板和友元全部内容,希望文章能够帮你解决c++之类模板和友元所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)