[英]Inheritance and member functions
Consider I have series of derived classes for example as listed below: 考虑一下,我有一系列派生类,例如下面所列:
class A
{
...
}
class B1 : public A //there may be many B's here say, B2, B3 etc
{
...
}
class C1 : public B1 //may be more C's as well
{
...
}
I would like to put all of the objects in single container, thus all would be of type class A
. 我想将所有对象放在单个容器中,因此所有对象都是
A
类类型。
Suppose I would like to add a function to class C1
, what would be the best way to achieve this? 假设我想向
C1
类添加一个函数,实现此目的的最佳方法是什么? My options would be introducing it in the base class A
and write the needed implementation in C1
, or, I could introduce it in C1
and do dynamic casting to access it. 我的选择是将其引入基类
A
并在C1
编写所需的实现,或者,我可以将其引入C1
并进行动态强制转换以对其进行访问。 Which one is preferred? 首选哪一个? Is dynamic casting too expensive?
动态铸造太昂贵了吗? (My main constrain is the run time.I have a flag in the base class to indicate what type of derived object it is, thus I do not have to dynamic cast every object in the container. Does adding unnecessary functions to base class can result in bad instruction cache use?)
(我的主要约束是运行时间。我在基类中有一个标志来指示它是什么类型的派生对象,因此不必动态转换容器中的每个对象。是否会在基类中添加不必要的功能在错误的指令缓存中使用?)
You don't tell us the purpose of the new function in C1
, and this does affect the answer, but as rough guidelines: 您没有告诉我们
C1
新功能的目的,但这确实会影响答案,但作为粗略的指导原则:
A
. A
C
series of classes but it can follow some general pattern (for example post-processing), add a post_process
method to A
, override it in C1
, and have that method call private implementation methods of C1
to do the actual specific post-processing task. C
系列类, 但是它可以遵循某些常规模式(例如,后处理),则将post_process
方法添加到A
,在C1
覆盖它,并使该方法调用C1
私有实现方法以完成实际的特定后处理任务。 adding a virtual function to your base class A is better because: 向基类A添加虚拟函数会更好,因为:
you should avoid dynamic cast especially in performance sensitive code. 您应该避免动态转换,尤其是在对性能敏感的代码中。 Please see Performance of dynamic_cast?
请查看dynamic_cast的性能?
you should avoid having conditions to examine the object type (eg is it A, B1, or C1 ?) before performing a type-specific operation. 在执行特定于类型的操作之前,应避免有条件检查对象类型(例如,A,B1或C1吗?)。 Not only because it's slow, but also because if you do so, every time you add a new object type (eg C2) you will need to check all those conditions to see if they need to be updated.
不仅因为它很慢,而且还因为这样做,每次添加新的对象类型(例如C2)时,您都需要检查所有这些条件以查看是否需要更新。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.