我是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()时动态创建组件子类对象,并释放每次请求进入时动态分配的内存。此方法最终为每个请求创建对象并可能达到性能(分配) &amp; free)并且可能导致内存碎片化。
在请求对象内静态创建组件子类对象,并将其引用指向组件数组。我不确定这是不是一个好主意,但通过重用相同的对象来解决问题。而且我不确定如何以简单而优雅的方式实现这一目标?任何建议都会有所帮助。
谢谢
答案 0 :(得分:1)
首先做最简单的解决方案。
选项1 可能会达到效果。这是一个很大的可能。如果我是你,我会使用这种方法,因为它更简单。
如果您遇到性能问题,如果,您可以证明它是分配&amp;只有当你考虑优化解决方案时才会导致它自由。
你想要的最后一件事是不必要的复杂代码。