04737_C++程序设计_第8章_多态性和虚函数

2023-02-18,,,

例8.1

分析下面程序的输出结果。

例8.2

分别使用指针和引用的display函数

 #include <iostream>

 using namespace std;

 const double PI = 3.14159;

 class Point
{
private:
double x, y;
public:
Point(double i, double j)
{
x = i;
y = j;
}
virtual double area()
{
return ;
}
}; class Circle :public Point
{
private:
double radius;
public:
Circle(double a, double b, double r) :Point(a, b)
{
radius = r;
}
double area()
{
return PI*radius*radius;
}
}; void display(Point *p)
{
cout << p->area() << endl;
} void display(Point&a)
{
cout << a.area() << endl;
} void main()
{
Point a(1.5, 6.7);
Circle c(1.5, 6.7, 2.5); Point *p = &c;
Point &rc = c; display(a);
display(p);
display(rc); system("pause");
};

例8.3

在构造函数和析构函数中调用虚函数。

 #include <iostream>

 using namespace std;

 class A
{
public:
A()
{ }
virtual void func()
{
cout << "Constructing A" << endl;
}
~A()
{ }
virtual void fund()
{
cout << "Destructor A" << endl;
}
}; class B :public A
{
public:
B()
{
func();
}
void fun()
{
cout << "Come here and go...";
func();
}
~B()
{
fund();
}
}; class C :public B
{
public:
C()
{ }
void func()
{
cout << "Class C" << endl;
}
~C()
{
fund();
}
void fund()
{
cout << "Destructor C" << endl;
}
}; void main()
{
C c;
c.fun(); system("pause");
};

例8.5

多重继承使用虚函数。

 #include <iostream>

 using namespace std;

 class A
{
public:
virtual void f()
{
cout << "Call A" << endl;
}
}; class B
{
public:
virtual void f()
{
cout << "Call B" << endl;//必须使用virtual声明
}
}; class C :public A, public B
{
public:
void f()//可以省略关键字virtual
{
cout << "Call C" << endl;
}
}; void main()
{
A *pa;
B *pb;
C *pc, c; pa = &c;
pb = &c;
pc = &c; pa->f();//输出Call C
pb->f();//输出Call C
pc->f();//输出Call C system("pause");
};

04737_C++程序设计_第8章_多态性和虚函数的相关教程结束。

《04737_C++程序设计_第8章_多态性和虚函数.doc》

下载本文的Word格式文档,以方便收藏与打印。