c++ - 如何创建具有接口函数的库供用户在 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
};
解决方案
从类 A 和 B 的定义中删除它。让共享 linrary 的用户提供它的实现 - 他们需要这样做,因为该函数在 Product 类中是纯虚拟的。
这个想法是只提供必须实现的接口。
推荐阅读
- html - div需要居中
- java - java:将 HTML 转换为 PDF 处理失败,并且有 itext
- ios - 设置 UICollectionView 的 NumberOfItemsInSection
- java - 如何使用在我的 Windows 机器上运行的 java 代码写入 linux 中的文件?
- javascript - 获取学生id数组
- .net - .net 应用程序崩溃而没有错误
- javascript - Ace Editor 自动调整同一页面上的 2 个编辑器窗口,一个可以完美运行
- php - 使用不同的 php 脚本获取 wp_loggedin 值,然后在 Android 应用程序中返回值
- php - laravel 5.3 托管问题 - 不加载 css
- bash - 由于缺少 #!/bin/bash?