C++ 中虚拟公共类的副作用
Virtual Public Class用于类,保证一个类的一个对象只继承一个子对象。
class L { /* ... */ }; // indirect base class
class B1 : virtual public L { /* ... */ };
class B2 : virtual public L { /* ... */ };
class D : public B1, public B2 { /* ... */ }; // valid
当我们不将 virtual public 用于单继承时,我们会产生副作用吗?例如,
class L { /* ... */ }; // indirect base class
class B1 : virtual public L { /* ... */ };
class D : public B1 { /* ... */ }; // valid
与 相同吗
class L { /* ... */ }; // indirect base class
class B1 : public L { /* ... */ };
class D : public B1 { /* ... */ }; // valid
?我的意思是,对于所有可能的情况,将父类设为虚拟是否安全?
Virtual Public Class is used for a class to ensure that an object of a class inherits only one subobject.
class L { /* ... */ }; // indirect base class
class B1 : virtual public L { /* ... */ };
class B2 : virtual public L { /* ... */ };
class D : public B1, public B2 { /* ... */ }; // valid
Do we have side effect when we use virtual public when we don't use it for single inheritance. For example, is
class L { /* ... */ }; // indirect base class
class B1 : virtual public L { /* ... */ };
class D : public B1 { /* ... */ }; // valid
the same as
class L { /* ... */ }; // indirect base class
class B1 : public L { /* ... */ };
class D : public B1 { /* ... */ }; // valid
? I mean, is it just safe to make the parent class as virtual for all possible cases?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
“以防万一”将父类设为虚拟也是安全的。该标准没有指定如何实现虚拟继承,但可能会对性能造成轻微影响。除非您正在编写对性能至关重要的内容,否则您不需要担心它。
It's just as safe to make the parent class virtual "just in case." The standard doesn't specify how virtual inheritance will be implemented, but there will probably be a slight performance hit. Unless you're writing something performance-critical, you shouldn't need to worry about it.
http://www.phpcompiler.org/articles/virtualinheritance.html
这与虚拟函数不同。
http://www.phpcompiler.org/articles/virtualinheritance.html
Not unlike virtual functions.