C++多态基础性练习

/*******************************************/
/*动态多态、虚函数
要求:
1.定义Shape类,成员函数:calcArea(),构造函数、析构函数
2.定义Rec类,成员函数:calArea(),构造函数、析构函数
数据成员:m_dWidth,m_dHeight
3.定义Circle类,成员函数:calArea(),构造函数、析构函数
数据成员:m_dR
*/
/******************************************/
思考:
1.不加同名函数前不加virtual关键字
Shape*shape1 = new Rect(3,5);
Shape *shape2 = new Circle(5);
shape1->calcArea();
shape2->calcArea();
运算结果:调用计算面积函数时,均调用的是父类的计算函数
这里写图片描述

2.加上virtauala关键字后,调用子类计算函数
代码:
//头文件

#include<iostream>
#include<stdlib.h>
#include<string>

using namespace std;

class Shape
{
public:
    Shape();
    ~Shape();
    double calcArea();

};


class Circle:public Shape
{
public:
    Circle(double r);
    ~Circle();
     double calcArea();
protected:
    double m_dR;

};
class Rect :public Shape
{
    public:
        Rect(double width,double height);
        ~Rect();
         double calcArea();
    protected:
    double m_dWidth;
    double m_dHeight;

};

//定义部分:

#include"Mult.h"

Shape::Shape()
{
    cout << "Shape()" << endl;
}
Shape::~Shape()
{

    cout << "~Shape()" << endl;
}
double Shape::calcArea()
{

    cout << " Shape->calcArea()" << endl;
    return 0;
}


Circle::Circle(double r)
{
    m_dR = r;
    cout << "Circle()" << endl;

}
Circle::~Circle()
{
    cout << "~Circle()" << endl;

}
double Circle::calcArea()
{
    cout << "Circle->calcArea()" << endl;
    return 3.14*m_dR*m_dR;
}

Rect::Rect(double width, double height)
{
    m_dWidth = width;
    m_dHeight = height;
    cout << "Rect()" << endl;
}
Rect::~Rect()
{
    cout << "~Rect()" << endl;
}
double Rect::calcArea()
{
    cout << "Rect->calcArea()" << endl;
    return m_dWidth*m_dHeight;
}

//测试部分

#include"Mult.h"
int main(void)
{
    Shape*shape1 = new Rect(3,5);
    Shape *shape2 = new Circle(5);
    shape1->calcArea();
    shape2->calcArea();

    delete shape1;
    shape1 = NULL;
    delete shape2;
    shape2 = NULL;

    system("pause");
    return 0;
}

运算结果:
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值