简体   繁体   English

继承和成员函数

[英]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新功能的目的,但这确实会影响答案,但作为粗略的指导原则:

  • If the new function is a general behavior that you may need on any object and C1 happens to be the first user, definitely just add the interface to A . 如果新功能是您可能需要在任何对象上执行的常规操作,并且C1恰好是第一个用户,则肯定要将接口添加到A
  • If the new function is specific to the 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私有实现方法以完成实际的特定后处理任务。
  • If neither of these are the case you may wish to reconsider your use of inheritance as it's possible you're using it to represent a relationship other than substitution. 如果这两种情况都不是,则您可能希望重新考虑继承的使用,因为您可能会使用它来表示替代关系。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM