Item 3:Never treat arrays polymorphically.(More Effective C++)
时间:2011-06-07 来源:Ray Z
1 #include <iostream>
2
3 using namespace std;
4
5 class BST
6 {
7 private:
8 int a;
9
10 public:
11 BST(int n) : a(n){};
12 int getData() { return a; }
13 friend ostream& operator<<(ostream &os, BST &bst);
14 };
15
16 ostream& operator<<(ostream &os, BST &bst)
17 {
18 cout << bst.getData();
19 return os;
20 }
21
22 class BalancedBST : public BST
23 {
24 private:
25 int number;
26
27 public:
28 BalancedBST(int n1, int n2) : BST(n1), number(n2){}
29 };
30
31 void print(BST b[], int count)
32 {
33 for(int i=0; i<count; i++)
34 {
35 cout << b[i] << endl;
36 }
37 }
38
39 int main()
40 {
41 BalancedBST bb1(1,3);
42 BalancedBST bb2(2,4);
43 BalancedBST a[2] = {bb1, bb2};
44 BST b[2] = {bb1, bb2};
45 print(a, 2);
46 print(b, 2);
47
48 cin.get();
49 return 0;
50 }
2
3 using namespace std;
4
5 class BST
6 {
7 private:
8 int a;
9
10 public:
11 BST(int n) : a(n){};
12 int getData() { return a; }
13 friend ostream& operator<<(ostream &os, BST &bst);
14 };
15
16 ostream& operator<<(ostream &os, BST &bst)
17 {
18 cout << bst.getData();
19 return os;
20 }
21
22 class BalancedBST : public BST
23 {
24 private:
25 int number;
26
27 public:
28 BalancedBST(int n1, int n2) : BST(n1), number(n2){}
29 };
30
31 void print(BST b[], int count)
32 {
33 for(int i=0; i<count; i++)
34 {
35 cout << b[i] << endl;
36 }
37 }
38
39 int main()
40 {
41 BalancedBST bb1(1,3);
42 BalancedBST bb2(2,4);
43 BalancedBST a[2] = {bb1, bb2};
44 BST b[2] = {bb1, bb2};
45 print(a, 2);
46 print(b, 2);
47
48 cin.get();
49 return 0;
50 }
相关阅读 更多 +