C++实验:多态性与虚函数

本文档详细介绍了C++实验,重点探讨了多态性、虚函数、静态关联和动态关联的概念。实验包括创建Point、Circle和Cylinder类的继承关系,分析虚函数在不同情况下的行为,以及实现抽象基类Shape及其派生类的面积计算。通过具体的源代码和运行结果,展示了多态性在实际编程中的应用。
摘要由CSDN通过智能技术生成

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
  • 3
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阡陌笙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值