例8.1
分析下面程序的输出结果。
例8.2
分别使用指针和引用的display函数。
1 #include <iostream> 2 3 using namespace std; 4 5 const double PI = 3.14159; 6 7 class Point 8 { 9 private: 10 double x, y; 11 public: 12 Point(double i, double j) 13 { 14 x = i; 15 y = j; 16 } 17 virtual double area() 18 { 19 return 0; 20 } 21 }; 22 23 class Circle :public Point 24 { 25 private: 26 double radius; 27 public: 28 Circle(double a, double b, double r) :Point(a, b) 29 { 30 radius = r; 31 } 32 double area() 33 { 34 return PI*radius*radius; 35 } 36 }; 37 38 void display(Point *p) 39 { 40 cout << p->area() << endl; 41 } 42 43 void display(Point&a) 44 { 45 cout << a.area() << endl; 46 } 47 48 void main() 49 { 50 Point a(1.5, 6.7); 51 Circle c(1.5, 6.7, 2.5); 52 53 Point *p = &c; 54 Point &rc = c; 55 56 display(a); 57 display(p); 58 display(rc); 59 60 system("pause"); 61 };
例8.3
在构造函数和析构函数中调用虚函数。
1 #include <iostream> 2 3 using namespace std; 4 5 class A 6 { 7 public: 8 A() 9 { 10 11 } 12 virtual void func() 13 { 14 cout << "Constructing A" << endl; 15 } 16 ~A() 17 { 18 19 } 20 virtual void fund() 21 { 22 cout << "Destructor A" << endl; 23 } 24 }; 25 26 class B :public A 27 { 28 public: 29 B() 30 { 31 func(); 32 } 33 void fun() 34 { 35 cout << "Come here and go..."; 36 func(); 37 } 38 ~B() 39 { 40 fund(); 41 } 42 }; 43 44 class C :public B 45 { 46 public: 47 C() 48 { 49 50 } 51 void func() 52 { 53 cout << "Class C" << endl; 54 } 55 ~C() 56 { 57 fund(); 58 } 59 void fund() 60 { 61 cout << "Destructor C" << endl; 62 } 63 }; 64 65 void main() 66 { 67 C c; 68 c.fun(); 69 70 system("pause"); 71 };
例8.5
多重继承使用虚函数。
1 #include <iostream> 2 3 using namespace std; 4 5 class A 6 { 7 public: 8 virtual void f() 9 { 10 cout << "Call A" << endl; 11 } 12 }; 13 14 class B 15 { 16 public: 17 virtual void f() 18 { 19 cout << "Call B" << endl;//必须使用virtual声明 20 } 21 }; 22 23 class C :public A, public B 24 { 25 public: 26 void f()//可以省略关键字virtual 27 { 28 cout << "Call C" << endl; 29 } 30 }; 31 32 void main() 33 { 34 A *pa; 35 B *pb; 36 C *pc, c; 37 38 pa = &c; 39 pb = &c; 40 pc = &c; 41 42 pa->f();//输出Call C 43 pb->f();//输出Call C 44 pc->f();//输出Call C 45 46 system("pause"); 47 };