首页 > 解决方案 > 如何创建具有接口函数的库供用户在 C++ 中定义?

问题描述

例如,如果我想创建一个如下所示的共享库,但我想保留virtual void Work();未定义,以便让使用此库的人们自由地实现适合其环境的行为。
但我知道如果我Work()在这个库中未定义,编译器会出错。如何在 C++ 中实现这一点?
或者它只是一个糟糕的设计?

class Contaniner
{
public:
    void Factory(int code, int size)// Construct specified type
    {
        if(code == 1)
        {
            products.push_back((Product *)new A(size));
        }
        else if(code == 2)
        {
            products.push_back((Product *)new B(size));
        }
    }
    void Init()// Run every product's AdjustSize() function
    {
        for(auto i : products)
        {
            i->AdjustSize();
        }
    }
    void Run()// Run every product's Work() function
    {
        for(auto i : products)
        {
            i->Work();
        }
    }
private:
    std::vector<Product *> products;
};

class Product
{
public:
    Product(int size) : m_size(size) { }
    virtual void AdjustSize() = 0;
    virtual void Work() = 0;
protected:
    int m_size;
};

class A : public Product
{
public:
    A(int size) : Product(size) {}
    virtual void AdjustSize() { //adjust the m_size }
    virtual void Work();// leave it to user to define
};

class B : public Product
{
public:
    B (int size) : Product(size) {}
    virtual void AdjustSize() { //adjust the m_size }
    virtual void Work();// leave it to user to define
};

标签: c++

解决方案


从类 A 和 B 的定义中删除它。让共享 linrary 的用户提供它的实现 - 他们需要这样做,因为该函数在 Product 类中是纯虚拟的。

这个想法是只提供必须实现的接口。


推荐阅读