c++ 计算几何图形面积(抽象类、虚函数的使用)

将一些类所具有的公共属性和方法放到基类中,避免重复定义。
定义基类Shape,在类中定义两个函数getName()、getArea()。分别用来获得类名称和面积。将getArea()定义为一个纯虚函数。

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

const double PI = 3.1415926;

class Shape
{
protected:
    char name[30];
public:
    Shape()
    {
        strcpy_s(name, "Shape");
    }
    char* getName()
    {
        return name;
    }

public:
    virtual double getArea() = 0;  //虚函数声明
};

class Circle: public Shape
{
private:
    double m_radius;
public:
    Circle(double radius)
    {
        strcpy_s(name, "Circle");
        m_radius = radius;
    }
    double getArea()
    {
        return PI * pow(m_radius, 2);
    }
};

class Rectangle: public Shape
{
private:
    double m_length;
    double m_width;
public:
    Rectangle(double length, double width)
    {
        m_length = length;
        m_width = width;
        strcpy_s(name, "Rectangle");
    }
    double getArea()
    {
        return m_length * m_width;
    }
};


void main(int argc, char* argv[])
{
    Circle circle(2);
    cout<<"shape name:"<<circle.getName()<<endl;
    cout<<"shape area:"<<circle.getArea()<<endl;
    Rectangle rectangle(3,2);
    cout<<"shape name:"<<rectangle.getName()<<endl;
    cout<<"shape area:"<<rectangle.getArea()<<endl;

    system("pause");
}

输出:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/akadiao/article/details/80165723
今日推荐