首页 > 技术文章 > 类模板与友元(10)

huanian 2020-04-28 10:03 原文

学习目标:

1.掌握类模板配合友元函数的类内实现和类外实现

----全局函数类内实现,即直接在类内声明友元(推荐)

 1 #include <iostream>
 2 #include <string>
 3 using namespace std;
 4 
 5 //通过全局函数 打印Person信息
 6 template<class T1,class T2>
 7 class Person
 8 {
 9     //全局函数 类内实现
10     friend void printPerson(Person<T1,T2> p)
11     {
12         cout << "姓名:" << p.m_Name << "年龄:" << p.m_Age << endl;
13     }
14 
15 public:
16 
17     Person(T1 name, T2 age)
18     {
19         this->m_Name = name;
20         this->m_Age = age;
21     }
22 
23 private:
24 
25     T1 m_Name;
26     T2 m_Age;
27 };
28 
29 //全局函数类内实现
30 void test_01(void)
31 {
32     Person<string, int>p("Tom", 18);
33     printPerson(p);
34 }
35 
36 int main(void)
37 {
38     test_01();
39 
40     system("pause");
41     return 0;
42 }

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

方式1:

1 //全局函数 类外实现 注意事项:
2 template<class T1,class T2> class Person;
3 
4 template<class T1, class T2> void printPerson2(Person<T1, T2> p);

方式2:

 1 //全局函数 类外实现 注意事项:
 2 template<class T1,class T2> class Person;
 3 
 4 //方式1:
 5 //template<class T1, class T2> void printPerson2(Person<T1, T2> p);
 6 
 7 //方式2:
 8 //全局函数类外实现
 9 template<class T1, class T2>
10 void printPerson2(Person<T1, T2> p)
11 {
12     cout << "姓名:" << p.m_Name << "年龄:" << p.m_Age << endl;
13 }

代码展示:

 1 #include <iostream>
 2 #include <string>
 3 using namespace std;
 4 
 5 //全局函数 类外实现 注意事项:
 6 template<class T1,class T2> class Person;
 7 
 8 //方式1:
 9 //template<class T1, class T2> void printPerson2(Person<T1, T2> p);
10 
11 //方式2:
12 //全局函数类外实现
13 template<class T1, class T2>
14 void printPerson2(Person<T1, T2> p)
15 {
16     cout << "姓名:" << p.m_Name << "年龄:" << p.m_Age << endl;
17 }
18 
19 //通过全局函数 打印Person信息
20 template<class T1,class T2>
21 class Person
22 {
23     //全局函数 类内实现
24     friend void printPerson1(Person<T1,T2> p)
25     {
26         cout << "姓名:" << p.m_Name << "年龄:" << p.m_Age << endl;
27     }
28 
29     //全局函数 类外实现
30     //要加一个空模板的参数列表
31     //如果全局函数 类外实现 需要让编译器知道这个函数的存在 声明在最前面
32     friend void printPerson2<>(Person<T1, T2> p);
33 
34 public:
35 
36     Person(T1 name, T2 age)
37     {
38         this->m_Name = name;
39         this->m_Age = age;
40     }
41 
42 private:
43 
44     T1 m_Name;
45     T2 m_Age;
46 };
47 
48 //全局函数类内实现
49 void test_01(void)
50 {
51     Person<string, int>p1("Tom", 20);
52     printPerson1(p1);
53 }
54 
55 //全局函数类外实现
56 void test_02(void)
57 {
58     Person<string, int>p2("Tom", 25);
59     printPerson2(p2);
60 }
61 
62 int main(void)
63 {
64     test_01();
65     test_02();
66 
67     system("pause");
68     return 0;
69 }

 

推荐阅读