What if you want a function of one class to be a friend of a second class, and a function of the second class to be a friend of the first class? How do you do it?
Make the bark() function of the dog class a friend of the cat class and the meow() function a friend of the dog class.
Example 5-8 - Mutual friends
1 // File: ex5-8.cpp
2
3 #include <iostream>
4 #include <cstring>
5 using namespace std;
6
7 class cat; // forward declare the cat class
8
9 class dog {
10 char name[10];
11 public:
12 void bark(const cat&) const;
13 dog(const char* n) { strcpy(name,n); }
14 friend class cat; // name the entire cat class as a friend
15 };
16
17 class cat {
18 char name[10];
19 public:
20 void meow(const dog&) const;
21 cat(const char* n) { strcpy(name,n); }
22 friend void dog::bark(const cat&) const;
23 };
24
25 // a dog barks at a cat exactly the number of times as
26 // the length of the cat's name
27 void dog::bark(const cat& c) const
28 {
29 for (unsigned i = 0; i < strlen(c.name); i++)
30 cout << " woof "; cout << endl;
31 }
32
33 // a cat meows at a dog exactly the number of times as
34 // the length of the dog's name
35 void cat::meow(const dog& d) const
36 {
37 for (unsigned i = 0; i < strlen(d.name); i++)
38 cout << " meow "; cout << endl;
39 }
40 main()
41 {
42 dog bart("Bart");
43 cat socks("Socks");
44
45 // Bart barks at Socks
46 bart.bark(socks);
47
48 // Socks meows at Bart
49 socks.meow(bart);
50
51 return 0;
52 }****** Output ******
woof woof woof woof woof
meow meow meow meow
沒有留言:
張貼留言