设为首页 加入收藏

TOP

C++多态基础性练习
2017-01-14 08:15:03 】 浏览:335
Tags:基础性 练习

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
  
   
#include
   
     #include
    
      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;
}

运算结果:

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇C++把输出结果写入到文件中 下一篇c++通过运算符[]重载实现一重和二..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目