为什么大多数OOP语言都没有覆盖静态方法? [英] Why is overriding of static methods left out of most OOP languages?

查看:93
本文介绍了为什么大多数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语言都没有覆盖静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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