避免虚拟功能 [英] Avoiding virtual functions

查看:70
本文介绍了避免虚拟功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,假设我要创建一系列类,每个类具有相同的成员函数.让我们调用函数

So suppose I want to make a series of classes that each have a member-function with the same thing. Let's call the function

void doYourJob();

我最终希望将所有这些类放入同一容器中,以便我可以遍历它们并让每个类都执行'doYourJob()'

I want to eventually put all these classes into the same container so that I can loop through them and have each perform 'doYourJob()'

显而易见的解决方案是使用该函数创建一个抽象类

The obvious solution is to make an abstract class with the function

 virtual void doYourJob();

但是我很犹豫.这是一个耗时的程序,而虚函数会使其变得更加稀薄.而且,此函数是类之间唯一的共同点,并且对于每个类,doYourJob的实现方式完全不同.

but I'm hesitant to do so. This is a time-expensive program and a virtual function would slime it up considerably. Also, this function is the only thing the classes have in common with each other and doYourJob is implimented completely differently for each class.

有没有一种方法可以避免将抽象类与虚函数一起使用?还是我不得不把它吸起来?

Is there a way to avoid using an abstract class with a virtual function or am I going to have to suck it up?

推荐答案

虚拟函数的成本不高.它们是一个间接调用,基本上像一个函数指针.什么是性能成本在C ++类中有一个虚方法?

Virtual functions don't cost much. They are an indirect call, basically like a function pointer. What is the performance cost of having a virtual method in a C++ class?

如果您处于每个调用的每个周期都很重要的情况,那就是您在函数调用中所做的工作很少,而您是在性能关键型应用程序的内部循环中调用它的,则可能需要使用其他方法完全接近.

If you're in a situation where every cycle per call counts, that is you're doing very little work in the function call and you're calling it from your inner loop in a performance critical application you probably need a different approach altogether.

这篇关于避免虚拟功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆