c++ - 关于 C++ 中接口(interface)类的使用

标签 c++ interface polymorphism abstract-class

我对 C++ 中接口(interface)类的用法有疑问,但不知道它的名称以及如何搜索它。希望你能帮助我,好心。

我将尝试用一个简单的例子来说明我的问题。

我有 5 种不同的可能对象,例如三角形、正方形、矩形、五边形和六边形

所有这些对象都有共同的属性,所以我将有一个接口(interface)类Shape

现在,我想要的是:我将拥有一个 Shape 类对象,并且希望能够将它用作其他 5 个对象之一,因为在运行时进行了选择。

所以我做了类似下面的事情:

class Shape 
{
public:

    virtual int getArea()=0;

    virtual void setWidth(int w)
    {
        width = w;
    }

    virtual void setHeight(int h)
    {
        height = h;
    }


protected:
    int width;
    int height;
};



class Triangle: public Shape
{
public:

    int getArea()
    { 
        return (m_Width * m_Height)/2; 
    }

};

class Rectangle: public Shape
{
public:

    int getArea()
    { 
        return (m_Width * m_Height); 
    }

};

使用时,我只想创建一个Shape 的对象,并用其中一个派生类对其进行初始化。因此,从那时起,我希望它的行为像该对象的实例一样:

void main(){

 Shape* shape;

 std::string shapeType;

 std::cout<<"Enter Shape Type: triangle or rectangle."<<std::endl;

 std::cin>>shapeType;


 if (shapeType == "triangle")
     shape = new Triangle();
 else if (shapeType == "rectangle")
     shape = new Rectangle();


 shape->setWidth(5);
 shape->setHeight(7);

 std::cout<<shape->getArea()<<std::endl;


}

到这里没问题。问题从这里开始。这些派生类可能有不同的属性、方法。当我将这些方法添加到它们自己的类时,shape 对象无法(正确地)访问它。可以使用的另一种方法是将新的派生对象转换为形状对象,例如:

Triangle* triangle = (Triangle*)shape;
// now I can access own attributes of Triangle object.

但这并不是你想的那样处理它的好方法。除此之外,我只知道一种方法迫使我将所有这些属性写入 Shape 类并在需要的派生类中实现它们,如果不需要其他类,则将其实现为空。

对于这个问题,你有什么好的解决办法吗?我敢肯定会有,但我对这个主题没有那么多经验,所以希望你有一个适合我想要的解决方案。

提前致谢。

最佳答案

首先,您的Shape 不是接口(interface),而是基本实现类。将它们分开。

接口(interface)是一个只有纯虚方法和虚析构函数的抽象类:

struct IShape
{
    virtual int getArea() =0;
    virtual void setWidth(int w) =0;
    virtual void setHeight(int h) =0;
    // without virtual destructor you cannot
    // properly destroy object through IShape pointer
    virtual ~IShape() {}
};

现在让我们编写基本实现:

class CShapeBaseImpl : public IShape
{
public:
    void setWidth(int w) override { width_ = w; }
    void setHeight(int h) override { height_ = h; }
protected:
    int width_ = 0;
    int height_ = 0;
};

在大多数情况下,您希望创建一些具体的对象并仅通过它的界面来使用它。通常是通过 abstract factory pattern 完成的:

std::unique_ptr<IShape> CreateTriangle( int a, int b, int c )
{
    auto triangle = std::make_unique<Triangle>(a,b,c);
    // there you can work with it as Triangle
    return triangle;
}

CreateTriangle 返回后,最好忘记它是 Triangle。现在是 IShape

关于c++ - 关于 C++ 中接口(interface)类的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26400108/

相关文章:

c# - 基本 C# 接口(interface)问题

c++ - 多态性奇怪的输出

java - Java中的重载和多分派(dispatch)

c++ - 将 basic_string<unsigned char> 转换为 basic_string<char> ,反之亦然

c++ - 括号可以将任意标识符作为参数吗? C++

java - 对象类、java API

c++ - 数据类型 inst 转换正确吗?

c++ - MFC - 打印 - 从自定义页面设置对话框更改页面方向

c++ - 是什么导致样式表渗入子小部件

java - 'natural ordering' 的含义及其与 compareTo() 方法的关系