c++ telescoping constructor is NOT supported until c++11

Telescoping constructor: see Effective Java 2nd Edition Item 2

If you want to use telescoping constructor but your compiler does not support c++11 standards, you can use default parameter instead, see code snippets 'main.cpp', 'Box.h', 'Box.cpp'.

If your compiler supports c++11 standards, the syntax of telescoping is shown in code snippet 'Box2.h' and 'Box2.cpp', and you might need to use '-std=c++11' parameter when you are compiling your source code.

For now, I'd like to use default parameter.

main.cpp

 1 #include "Box.h"
 2 
 3 int main()
 4 {
 5     Box box;
 6     box.print();
 7     Box box2(1);
 8     box2.print();
 9     Box box3(1, 'A');
10     box3.print();
11     Box box4(1, 'A', 1.88);
12     box4.print();
13     return 0;
14 }

 

Box.h

 1 #ifndef BOX_H
 2 #define BOX_H
 3 
 4 class Box
 5 {
 6     public:
 7         Box(const int &_a = 0, const char &_b = 'M', const double &_c = 0.99);
 8         ~Box();
 9         void print();
10 
11     private:
12         int a;
13         char b;
14         double c;
15 };
16 
17 #endif // BOX_H

 

Box.cpp

 1 #include "Box.h"
 2 
 3 #include <iostream>
 4 
 5 using namespace std;
 6 
 7 Box::Box(const int &_a, const char &_b, const double &_c)
 8 : a(_a), b(_b), c(_c)
 9 {
10 
11 }
12 
13 Box::~Box()
14 {
15 
16 }
17 
18 void Box::print() {
19     cout << "a = " << a << ",b = " << b << ",c = " << c << endl;
20 }

Box2.h

 1 #ifndef BOX_H
 2 #define BOX_H
 3 
 4 class Box
 5 {
 6     public:
 7         Box(const int &_a, const char &_b, const double &_c);
 8         Box(const int &_a, const char &_b);
 9         Box(const int &_a);
10         Box();
11         ~Box();
12         void print();
13 
14     private:
15         int a;
16         char b;
17         double c;
18 };
19 
20 #endif // BOX_H

 

Box2.cpp

 1 #include "Box.h"
 2 
 3 #include <iostream>
 4 
 5 using namespace std;
 6 
 7 Box::Box(const int &_a, const char &_b, const double &_c)
 8 : a(_a), b(_b), c(_c)
 9 {
10 
11 }
12 
13 Box::Box(const int &_a, const char &_b)
14 : Box(_a, _b, 0.99)
15 {
16 
17 }
18 
19 Box::Box(const int &_a)
20 : Box(_a, 'M')
21 {
22 
23 }
24 
25 Box::Box()
26 : Box(0)
27 {
28 
29 }
30 
31 Box::~Box()
32 {
33 
34 }
35 
36 void Box::print() {
37     cout << "a = " << a << ",b = " << b << ",c = " << c << endl;
38 }

 

posted @ 2014-11-20 17:12  rldts  阅读(338)  评论(0编辑  收藏  举报