C++学习历程(六)构造函数与析构函数(纯虚函数)


基类为图形类:包含长,宽,半径;
派生类Circle  :用来求圆的面积;
派生类Square :用来求矩形面积;

#include <iostream>
#define PI 3.1415926
using namespace std;

class Graph
{
    protected:
        int m_a,m_b;
        int m_r;
    public:
        Graph(int a,int b,int r);
        virtual void CircleArea() = 0; //纯虚函数i
        virtual void SquareArea() = 0;  
        ~Graph();
};

Graph::Graph(int a,int b,int r)
{
    cout << "Graph Consturctor!" << endl;
    m_a = a;
    m_b = b;
    m_r = r;
}

Graph::~Graph()
{
    cout << "Graph Desconstructor!" << endl;
}

class Circle : public Graph
{
    public:
        Circle(int a,int b,int r);
        void CircleArea();  //继承下来的纯虚函数必须有函数体,否则此类也会成为抽象类
        void SquareArea()    //抽象类则无法创建对象
        {
            
        }
        ~Circle();
};

Circle::Circle(int a,int b,int r) : Graph(a,b,r)
{
    cout << "Circle Constructor!" << endl;
}

void Circle::CircleArea()
{
    cout << "The Circle's mianji is : " << m_r * m_r * PI << endl;
}

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

class Square : public Graph
{
    public:
        Square(int a,int b,int r);
        void CircleArea()
        {

        }
        void SquareArea();
        ~Square();
};

Square::Square(int a,int b,int r) : Graph(a,b,r)
{
    cout << "Square Constructor!" << endl;
}

void Square::SquareArea()
{
    cout << "The Square's mianji is : " << m_a * m_b << endl; 
}

Square::~Square()
{
    cout << "Square Desconstructor!" << endl;
}


int main(int argc, char **argv)
{
    /*Circle a(3,5,7);
    Square b(3,5,8);

    a.CircleArea();
    b.SquareArea();*/
    Graph *pg = new Circle(3, 5, 7);  //向上转型,派生类地址赋值给基类指针,则基类可以调用派生类函数
    return 0;
}

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页