How do you declare an interface in C++?

前端 未结 15 2569
借酒劲吻你
借酒劲吻你 2020-11-22 03:26

How do I setup a class that represents an interface? Is this just an abstract base class?

15条回答
  •  广开言路
    2020-11-22 04:07

    class Shape 
    {
    public:
       // pure virtual function providing interface framework.
       virtual int getArea() = 0;
       void setWidth(int w)
       {
          width = w;
       }
       void setHeight(int h)
       {
          height = h;
       }
    protected:
        int width;
        int height;
    };
    
    class Rectangle: public Shape
    {
    public:
        int getArea()
        { 
            return (width * height); 
        }
    };
    class Triangle: public Shape
    {
    public:
        int getArea()
        { 
            return (width * height)/2; 
        }
    };
    
    int main(void)
    {
         Rectangle Rect;
         Triangle  Tri;
    
         Rect.setWidth(5);
         Rect.setHeight(7);
    
         cout << "Rectangle area: " << Rect.getArea() << endl;
    
         Tri.setWidth(5);
         Tri.setHeight(7);
    
         cout << "Triangle area: " << Tri.getArea() << endl; 
    
         return 0;
    }
    

    Result: Rectangle area: 35 Triangle area: 17

    We have seen how an abstract class defined an interface in terms of getArea() and two other classes implemented same function but with different algorithm to calculate the area specific to the shape.

提交回复
热议问题