为什么大多数OOP语言都没有覆盖静态方法?

编程入门 行业动态 更新时间:2024-10-17 11:25:48
本文介绍了为什么大多数OOP语言都没有覆盖静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这当然不是一个好的OOP设计-因为从概念上讲,对派生类的所有实例的通用行为的需求是相当有效的.而且,如果只说Data.parse(file),在基类中具有通用的parse()代码并让其重写比必须在所有数据子类型中实现大部分相似的代码要小心得多,那将使代码变得更加简洁.叫DataSybtype.parse(file)-丑陋丑陋

It is certainly not for good OOP design - as the need for common behavior of all instances of a derived class is quite valid conceptually. Moreover, it would make for so much cleaner code if one could just say Data.parse(file), have the common parse() code in the base class and let overriding do its magic than having to implement mostly similar code in all data subtypes and be careful to call DataSybtype.parse(file) - ugly ugly ugly

因此必须有一个原因-例如性能?

So there must be a reason - like Performance ?

作为奖励-是否有OOP语言允许这样做?

As a bonus - are there OOP languages that do allow this ?

欢迎使用特定于Java的参数,因为这是我所习惯的-但我相信答案是与语言无关的.

Java-specific arguments are welcome as that's what I am used to - but I believe the answer is language agnostic.

理想情况下:

<T> void method(Iface<? extends T> ifaceImpl){ T.staticMeth(); // here the right override would be called }

这也会由于擦除而失败(至少在Java中是这样)-如果擦除正在进行,则需要(将需要)实际通过该类:

This will also fail due to erasure (in java at least) - if erasure is at work one needs (would need) to actually pass the class :

<T, K extends T> void method(Iface<K> ifaceImpl, Class<K> cls){ cls.staticMeth(); // compile error }

这有意义吗?已经有语言在这样做吗?除了反射之外,还有其他解决方法吗?

Does it make sense ? Are there languages doing this already ? Is there a workaround apart from reflection ?

推荐答案

与C ++对话

class Foo { public: static void staticFn(int i); virtual void virtFn(int i); };

虚函数是成员函数-即使用this指针进行调用,从中可以查找vtable并找到要调用的正确函数.

The virtual function is a member function - that is, it is called with a this pointer from which to look up the vtable and find the correct function to call.

静态函数显式地不对成员进行操作,因此没有this对象可从中查询vtable.

The static function, explicitly, does not operate on a member, so there is no this object from which to look up the vtable.

当您如上所述调用静态成员函数时,您将显式提供一个固定的静态函数指针.

When you invoke a static member function as above, you are explicitly providing a fixed, static, function pointer.

foo->virtFn(1);

扩展到类似的内容

foo->_vtable[0](foo, 1);

同时

foo->staticFn(1);

扩展为简单的函数调用

Foo@@staticFn(1);

静态"的全部要点是它与对象无关.因此,不可能进行虚拟化.

The whole point of "static" is that it is object-independent. Thus it would be impossible to virtualize.

更多推荐

为什么大多数OOP语言都没有覆盖静态方法?

本文发布于:2023-11-10 02:47:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1574131.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:静态   语言   方法   OOP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!