用抽象基类重用对象实现多态
C++ Reusing objects to achieve Polymorphism using Abstract Base class
我是c++的新手,我正在研究如何在一个特定的项目中使用多态性。
我有一个组件列表。每个组件都有一个与之相关的分数,该分数是使用逻辑计算的。所以我有一个抽象类:
class Component {
public:
int compute_score(request *r) =0;
int get_score() { return score; }
protected:
int score;
};
现在每个组件都继承这个抽象基类来实现自己的逻辑来计算组件的分数。最后的算法是将所有的Component分数合并。
// Compute and combine scores
for (int ndx = 0; ndx < num_components; ndx++) {
total += components[ndx]->compute_score();
}
combined_score = total/num_components;
现在我正试图将这个模型适合于现有的代码库。有一个叫做request的大结构体,我想在其中添加这些Component对象并计算分数。
struct request {
...
Component *components[num_components];
...
};
void serve(request *r) {
...
// Compute and combine scores
for (int ndx = 0; ndx < num_components; ndx++) {
total += components->compute_score();
}
combined_score = total/num_components;
...
}
// Listener
void start(request *r) {
// Listen for request
// Serve the request
serve(&r);
// Clear the request struct for reuse
memset(r, 0, sizeof(request));
}
int main() {
// Created only once and then reused
request *req = (request*) calloc(1, sizeof(calloc));
start(&req);
}
使用组件数组的可能性:
在调用serve()时动态创建组件子类对象,并释放每次请求进入时动态分配的内存。这种方法最终会为每个请求创建对象,并可能影响性能(分配&
在请求对象内部静态地创建组件子类对象,并将它们的引用指向组件数组。我不确定这是不是一个好主意,但通过重用相同的对象解决了这个问题。我不确定如何以一种简单而优雅的方式实现这一点?
谢谢
先做最简单的解决方案
选项1 可能影响性能。这是一个很大的可能。如果我是你,我会用那个方法,因为它更简单。
如果你遇到性能问题,如果你可以证明这是分配&只有这样,你才应该考虑优化解决方案。
您最不希望看到的是不必要的复杂代码。
相关文章:
- 如何在这个简单的最小示例中实现多态性?
- 使用连续内存实现多态性
- 实现后期多态性的最佳方法
- 将多态性与运算符 + 重载模板化类结合使用.如何实现基类?
- 为实体组件系统实现多态组件
- 多态性实现
- 在 C++ 中实现多态性有哪些不同的方法
- 具有多态数据的容器的常见实现是什么
- 可以使用不同的实现文件来实现多态性吗
- 如何使用多重继承实现多态行为
- 类中的多态函数,实现抽象类
- 如何在嵌套类中实现多态性
- 我们可以通过const函数实现多态性吗
- 用排序函数实现多态性
- 如何:在打印函数中实现多态性
- 用抽象基类重用对象实现多态
- 使用模板实现多态性
- 以惯用的方式实现多态运算符==(C++)
- 为什么一个structclass需要一个虚方法来实现多态?
- 技术实现多态性,但节省4字节