1 //课本习题8-5
2 #include <iostream>
3 #include <string>
4 using namespace std;
5 class Mammal
6 {
7 public:
8 virtual void speak()
9 {
10 cout<<"动物正在说话"<<endl;
11 }
12 };
13 class Dog:public Mammal
14 {
15 public:
16 void speak()
17 {
18 cout<<"dog正在说话"<<endl;
19 }
20 };
21 void test()
22 {
23 Dog d;
24 d.speak();
25 Mammal m;
26 m.speak();
27 }
28 int main()
29 {
30 test();
31 return 0;
32 }
1 //课本习题8-6
2 #include <iostream>
3 #include <string>
4 using namespace std;
5 class Shape
6 {
7 public:
8 virtual float getArea() = 0;
9 virtual float getPerim() = 0;
10 };
11 class Rectangle:public Shape
12 {
13 public:
14 Rectangle(float L,float W)
15 {
16 l = L;
17 w = W;
18 }
19 float getArea()
20 {
21 cout<<"rectangle的面积:"<<l*w<<endl;
22 return l*w;
23 }
24 float getPerim()
25 {
26 cout<<"rectangle的周长:"<<(l+w)*2<<endl;
27 return (l+w)*2;
28 }
29 protected:
30 float l;
31 float w;
32 };
33 class Circle:public Shape
34 {
35 public:
36 Circle(float R)
37 {
38 r = R;
39 }
40 float getArea()
41 {
42 cout<<"circle的面积:"<<3.14*r<<endl;
43 return 3.14*r;
44 }
45 float getPerim()
46 {
47 cout<<"circle的周长:"<<2*3.14*r<<endl;
48 return 2*3.14*r;
49 }
50 protected:
51 float r;
52 };
53 void test()
54 {
55 Rectangle r(2,3);
56 Circle c(5);
57 r.getArea();
58 r.getPerim();
59 c.getArea();
60 c.getPerim();
61 }
62 int main()
63 {
64 test();
65 return 0;
66 }
1 //课本习题8-7
2 //运行失败
3 #include <iostream>
4 using namespace std;
5 class Point
6 {
7 friend ostream& operator<<(ostream &cout,Point p);
8 public:
9 Point()
10 {
11 m_Num = 0;
12 }
13 //前置++
14 Point& operator++()
15 {
16 m_Num++;
17 return *this;
18 }
19 //后置++
20 Point operator++(int)
21 {
22 Point temp = *this;
23 m_Num++;
24 return temp;
25 }
26 //前置--
27 Point& operator--()
28 {
29 m_Num--;
30 return *this;
31 }
32 //后置--
33 Point operator--(int)
34 {
35 Point temp = *this;
36 m_Num--;
37 return temp;
38 }
39 private:
40 int m_Num;
41 };
42 ostream& operator<<(ostream& cout,Point p)
43 {
44 cout<<p;
45 return cout;
46 }
47 void test()
48 {
49 Point a;
50 cout<<"a++ = "<<a++<<endl;
51 cout<<"++a = "<<++a<<endl;
52 }
53 int main()
54 {
55 test();
56 return 0;
57 }