c++ - 静态函数和非虚拟方法可以被覆盖吗?什么是静态多态?

标签 c++ inheritance static polymorphism virtual

请查看此函数函数的输出。它表明静态函数可以被覆盖,因为派生类继承了函数:

void put(){printf("Static functions in base class");}

如果我们不覆盖 put() 输出是基类中的静态函数 但我们将其重写为:

void put(){printf("Static functions are overridden in derived class");}

所以输出是静态函数在派生类中被覆盖 公共(public):

#include<iostream>

class base{
public:
static void put(){printf("Static functions in base class");}
};

class derived : public base{
void put(){printf("Static functions are overridden in derived 
class");}    
};

int main(){
derived *bp = new derived;// Static Polymorphism //
bp->put();
return 0;
}

因为这里 put() 不是虚函数。那么我们可以覆盖非虚函数吗?

这是静态多态的情况吗?

最佳答案

Can static functions be overridden?

没有。

struct Base { static void f() {} };
struct Derived : Base { void f() {} };

Base::fDerived::f 是两个不同的函数,它们甚至不共享一个公共(public)接口(interface):正确的不带参数,后面的是隐藏的指向 Derived 的指针。

Can non virtual functions be overridden?

没有。

struct Base { void f() {} };
struct Derived : Base { void f() {} };

Derived::f 隐藏 Base::f 当您操作一个对象、对对象的引用或指向 Derived< 类型对象的指针时:

Derived d;
Derived& dref = d;
Derived* dptr = &d;
d.f(); // calls Derived::f
dref.f(); // calls Derived::f
dptr->f(); // calls Derived::f

Base& bref = d;
Base* bptr = &d;
bref.f(); // calls Base::f
bptr ->f(); // calls Base::f

关于c++ - 静态函数和非虚拟方法可以被覆盖吗?什么是静态多态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36081470/

相关文章:

c++ - fRead方法的差异

c++ - C++ 中的继承 : define variables in parent-child classes

C++,基类如何包含子类作为成员并调用其方法

java - 如何通过继承来访问string的值?

java - Java嵌套静态类

c++ - 下载文件前如何获取文件名

c++ - 如何删除输出末尾的逗号?

c++ - 使用模板模板参数的替代方法

c++ - extern const inside namespace 和 static const 类成员之间的区别?

python - Django - 为什么不提供图片