zoukankan      html  css  js  c++  java
  • C++纯虚函数、抽象类、纯抽象类

    #include<iostream>
    
    class Shape {  //抽象类
        //包含纯虚函数的类叫抽象类
        //不能使用抽象类创建对象
        //如果类中所有的成员函数都是纯虚函数,那么该类就是纯抽象类--也叫接口类--纯属给子类做接口的类
    
    public:
        Shape(int x = 0, int y = 0) :m_x(x), m_y(y) {    }
        virtual void draw(void) = 0;   //纯虚函数
        //自定义了接口,没有实现体的虚函数叫纯虚函数
        
    protected:
        int m_x; 
        int m_y; 
    };
    class Rect :public Shape {  
    public:
        Rect(int x, int y, int w, int h) :Shape(x, y), m_w(w), m_h(h) {}
        void draw(void) {  
            std::cout << "绘制矩形:" << m_x << ", " << m_y << ", " << m_w << ", " << m_h << std::endl;
        }
    private:
        int m_w;
        int m_h;
    };
    
    class Circle :public Shape {  
    public:
        Circle(int x, int y, int r) :Shape(x, y), m_r(r) {}
        void draw(void) {  
            std::cout << "绘制圆形:" << m_x << ", " << m_y << ", " << m_r << std::endl;
        }
    private:
        int m_r;
    };
    
    void render(Shape* buf[]) {
        for (int i = 0; buf[i] != NULL; ++i) {
            buf[i]->draw();
            
        }
    }
    
    int main()
    {
        Shape* buf[1024] = { NULL };  
        buf[0] = new Rect(100, 100, 200, 300);
        buf[1] = new Circle(100, 100, 50);
        buf[2] = new Rect(10, 80, 300, 30);
        buf[3] = new Circle(10, 150, 500);
        render(buf);
    
        return 0;
    }

    工厂模式

    #include<iostream>
    
    class PDF {
    public:
        void parse(const char* pdffile) {  //利用this指针实现多态的函数
            std::cout << "解析出一行文本" << std::endl;
            onText();
            std::cout << "解析出一副图片" << std::endl;
            onImage();
            std::cout << "解析出一个矩形" << std::endl;
            onRect();
    
        }
    
    private:
        virtual void onText(void) = 0;
        virtual void onImage(void) = 0;
        virtual void onRect(void) = 0;
    
    };
    
    class PDFRen :public PDF {
    private:
        void onText(void) {
            std::cout << "显示一行文本" << std::endl;
        }
        void onImage(void) {
            std::cout << "绘制一副图片" << std::endl;
        }
        void onRect(void) {
            std::cout << "绘制一个矩形" << std::endl;
        }
    };
    
    int main()
    {
        PDFRen r;
        r.parse("xx.pdf");
    
        return 0;
    }

  • 相关阅读:
    Web网页安全色谱
    控件继承
    加密(转摘)
    关于Chart控件X轴数据显示不全解决方法。
    orcle 创建表空间用户
    oracle REGEXP_REPLACE
    產生64位隨机無重復碼
    简单跨浏览器通信.
    [原創]加載動態JS文件.
    层的拖放
  • 原文地址:https://www.cnblogs.com/liming19680104/p/13602314.html
Copyright © 2011-2022 走看看