C++实验:多态性与虚函数
1. 实验目的
(1) 了解多态性的概念。
(2) 了解虚函数的作用及使用方法。
(3) 了解静态关联和动态关联的概念和用法。
(4) 了解纯虚函数和抽象类的概念和用法。
2.实验内容
事先编写好程序,上机调试和运行程序,分析结果。
(1)声明Point (点)类,由Point类派生出Circle (圆)类,再由Circle类派生出Cylinder (圆柱体)类。将类的定义部分分别作为3个头文件,对它们的成员函数的声明部分分别作为3个源文件( .cpp文件),在主函数中用#include命令把它们包含进来,形成一个完整的程序,并上机运行。
(2)在教材第12章例12.3的基础上作以下修改,并作必要的讨论。
A.把构造函数修改为带参数的函数,在建立对象时初始化。
B.先不将析构函数声明为virtual,在main函数中另设一个指向 Circle 类对象的指针变量,使它指向grad1.运行程序,分析结果。
C.不作第B点的修改而将析构函数声明为virtual,
运行程序,分析结果。
(3)声明抽象基类Shape, 由它派生出3个派生类: Circle (圆形)、Rectangle (矩形)、Triangle
(三角形),用一个函数printArea分别输出以上三者的面积,3个图形的数据在定义对象时给定。
3.源代码
//Point.h
#include<iostream>
using namespace std;
class Point
{
public:
Point(float =0,float =0);
void setPoint(float,float);
float getX() const{
return x;}
float getY() const{
return y;}
friend ostream &operator<<(ostream&,const Point &);
protected:
float x,y;
};
//Circle.h
#include"point.h"
using namespace std;
class Circle:public Point
{
public:
Circle(float x=0,float y=0,float r=0);
void setRadius(float);
float getRadius() const;
float area() const;
friend ostream &operator<<(ostream&,const Circle &);
protected:
float radius;
};
//Cylinder.h
#include<iostream>
#include"circle.h"
using namespace std;
class Cylinder:public Circle
{
public:
Cylinder(float x=0,float y=0,float r=0,float h=0);
void setHeight(float);
float getHeight() const;
float area() const;
float volume() const;
friend ostream&operator<<(ostream&,const Cylinder&);
protected:
float height;
};
//Point.cpp
#include"point.h"
Point::Point(float a