Example of polymorphism working with data structure in C++ based on php example

前端 未结 3 1798
日久生厌
日久生厌 2021-01-28 21:52

I am learning polymorphism and I am familiar with php.

I came across this excellent example from https://stackoverflow.com/a/749738/80353. reproduced below.

How

3条回答
  •  無奈伤痛
    2021-01-28 22:27

    Well, you can use a pointer with abstract classes using pure virtual methods like so:

    class Polygon {
        public:
            virtual void setValue(int k) = 0;    // Declaring our pure virtual method.
    };
    
    class Rect : public Polygon {
        public:
            virtual void setValue(int k); = 0;   // Declaring the pure virtual method again.
    };
    
    Rect::setValue(int k) {    // You must create a setValue() method for every class, since we made a pure virtual method. This is the Polymorphic part.
        // Code in here that setValue() method executes.
        int foo = a;
        std::cout << foo << std::endl;
    }
    

    Now you can access the methods declaring object pointers.

    int main() {
        Polygon* pSomePolygon = nullptr;   // Assuming using C++11.
        Rect* pRect = new Rect;    // Declare our object.
    
        pSomePolygon = pRect;    // Point our pointer to object 'pRect'.
    
        pSomePolygon->setValue(18);    // Pointer accesses pRect and uses the pure virtual method.
        delete pRect;    // Clean up!
    
        return 0;
    }
    

提交回复
热议问题