我是C++的新手,并想出如何为我正在处理的特定项目使用多态。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);
}
可能性使用组件阵列:
动态创建组件的子类对象,同时服务()被调用和免费这是动态分配的每一个请求到达时间的存储器这种方法。最终为每个请求创建对象,并可能达到性能(分配&空闲),并可能导致内存碎片。
在请求对象内静态创建组件子类对象,并将它们对组件数组的引用指向它们。我不确定这是否是一个好主意,但通过重复使用相同的对象来解决问题。我不知道如何以简单和优雅的方式实现这一目标?任何的意见都将会有帮助。
感谢
你首先说“我有一个组件列表”,后面说为了使用它,你必须创建子类对象。在我的理解中,数组中的指针将指向现有组件(以前曾以任何方式创建过)。对我而言,情况并不清楚。也就是说,你可能想索引组件并传递请求,对吧?即('组分[NDX] - > compute_score(R)')。 –
我想创建所有组件对象只有一次,并重复使用相同的每个请求进来。是否有一个很好的方法,使数组指针指向这些对象,如果他们都将在同一个结构? – mariner