2012年2月15日 星期三

Chaining Functions


Functions may be "chained" by returning a reference to the class type.

Example 5-2 - Chaining Functions

1      File: ex5-2.cpp
2     
3      #include <iostream>
4      using namespace std;
5     
6      class circle
7      {
8        private:
9            double radius;
10        public:
11            circle (double r) { radius = r;}        // constructor
12            circle& area(void);
13            circle& circumference(void);
14      };
15     
16      circle& circle::area(void)
17      {
18        cout<<"The area of the circle is "
19                << 3.14 * radius * radius << endl;
20        return (*this);
21      }
22     
23      circle& circle::circumference(void)
24      {
25        cout<<"The circumference of the circle is "
26                << 2. * 3.14 * radius << endl;
27        return (*this);                   // What if you cout << this ?
28      }
29     
30      int main(void)
31      {
32        circle c1(5);
33        c1.area().circumference();
34     
35        circle c2(4.45);
36        c2.circumference().area();
37        return 0;
38      }


******  Output  ******

The area of the circle is 78.5
The circumference of the circle is 31.4
The circumference of the circle is 27.946
The area of the circle is 62.1799

沒有留言:

張貼留言