If a method returns an interface, what does it mean?

后端 未结 4 1390
眼角桃花
眼角桃花 2021-01-18 11:38

I see many methods that specify an interface as return value. Is my thought true that it means: my method can return every class type that inherits from that interface? if n

4条回答
  •  一个人的身影
    2021-01-18 12:05

    C++ supports a programming technique called polymorphism. That is a derived class can look like a base class to other code that knows nothing about the derived classes. Take a look at his example:

    class Shape
    {
    public:
        virtual float Area () const = 0;
    };
    
    class Rectangle: public Shape
    {
    public:
        Rectangle (float width, float height)
            : m_width(width)
            , m_height(height)
        {}
    
        virtual float Area () const
        {
            return m_width * m_height;
        }
    
    private:
        float m_width;
        float m_height;
    };
    
    class Circle: public Shape
    {
    public:
        Circle (float radius)
            : m_radius(radius)
        {}
    
        virtual float Area () const
        {
            return 3.141592653f*(m_radius*m_radius);
        }
    
    private:
        float m_radius;
    };
    

    Now you can see from this code we've created a base class Shape (our interface) and two derived classes that specialise this class, one a rectangle, another a circle. Now let's create a function that prints out the area of a shape:

    void PrintArea (const Shape& shape)
    {
        printf("Area of shape = %f",shape.Area());
    }
    

    This function doesn't care if its a circle of rectangle. Or it cares about is that it's passed a shape and that you can get the area of it, regardless of type.

    So this code uses this function:

     Rectangle r (5.0f,4.0f);
     Circle c (25.0f);
    
     PrintArea(r);      // Print the area of the rectangle
     PrintArea(c);      // Print the area of the circle
    

    Hope this helps.

提交回复
热议问题