类模板与友元
1 /* 类模板与友元 */
2
3 #include<iostream>
4
5 using namespace std;
6
7 template<class T>class myclass;// 声明友元类的存在
8 template<class T>void show(myclass<T> my);// 友元函数的声明
9
10 template<class T>
11 class myclass
12 {
13 friend void show(myclass<double> my);// 友元函数
14 friend void show<T>(myclass<T> my);// 友元函数模板
15 public:
16 myclass(int a,int b,T m, T n):x(a),y(b),a(m),b(n)
17 {
18
19
20 }
21
22 private:
23 int x;
24 int y;
25
26 private:
27 T a;
28 T b;
29 };
30
31 void show(myclass<double> my)// 友元函数锁定了类型
32 {
33 cout << my.a << " " << my.b << " " << my.x << " " << my.y << endl;
34
35
36 }
37
38
39 template<class T>
40 void show(myclass<T> my)
41 {
42 cout << my.a << " " << my.b << " " << my.x << " " << my.y << endl;
45 }
46
47
48 void main()
49 {
50 myclass<double> my1(19,18,12.6,15.8);
51 myclass<int> my2(19,18,12,15);
52 show(my1);
53 show(my2);// 调用友元模板,自动识别类型
54
57 cin.get();
58 }
长风破浪会有时,直挂云帆济沧海
posted on 2015-06-12 15:34 Dragon-wuxl 阅读(113) 评论(0) 收藏 举报
浙公网安备 33010602011771号