美文网首页
(十二)Shape

(十二)Shape

作者: GoodTekken | 来源:发表于2023-03-28 22:41 被阅读0次
#include <string>
#include <iostream>

using namespace std;

class Shape
{
    public:
        Shape(const string name)
        {
            m_name = name;
        }
        ~Shape()
        {

        }

        virtual void paint() = 0;    //(1)

        string getName() const
        {
            return m_name;
        }

    private:
        string m_name;
};

//Box 和 Line 类的定义与Ellipse类似,其代码略
class Box : public Shape
{
    public:
        Box(const string name):Shape(name)
        {
            cout << "Box" << endl;
        }

        void paint()
        {
            cout << getName() << endl;
        }
};

class Line : public Shape
{
    public:
        Line(const string name):Shape(name)
        {
            cout << "Line" << endl;
        }

        void paint()
        {
            cout << getName() << endl;
        }
};

class Ellipse : public Shape   //(2)
{
    public:
        Ellipse(const string name):Shape(name)
        {
            cout << "Ellipe" << endl;
        }

        void paint()
        {
            cout << getName() << endl;
        }
};

class Circle : public Ellipse   //(3)
{
    public:
        Circle(const string& name):Ellipse(name)
        {
            cout << "Circle" << endl;
        }
};

class Diagram
{
    public:
        void drawAShape(Shape* shape)
        {
            shape->paint();
        }

        void drawShapes()
        {
            shapes[0] = new Circle("C");
            shapes[1] = new Ellipse("F");
            for(int i = 0; i < 2; i++ )
            {
                drawAShape(shapes[i]);
            }
        }

        void close()
        {
            ;  /*删除形状*/
        }

    private:
        Shape* shapes[2];
};

int main()
{
    Diagram* diagram = new Diagram();   //(4)
    diagram->drawShapes();
    diagram->close();

    delete diagram;   //(5)

    return 0;
}

答案:
(1)virtual

(2):public Shape

(3):public Ellipse

(4)new Diagram()

(5)delete

相关文章

网友评论

      本文标题:(十二)Shape

      本文链接:https://www.haomeiwen.com/subject/chjordtx.html