虚函数const vs虚函数非const [英] virtual function const vs virtual function non-const

查看:221
本文介绍了虚函数const vs虚函数非const的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Base
{
   public:
   virtual void func() const
   {
     cout<<"This is constant base "<<endl;
   }
};

class Derived : public Base
{
   public:
   virtual void func()
   {
     cout<<"This is non constant derived "<<endl;
   }
};


int main()
{
  Base *d = new Derived();
  d->func();
  delete d;

  return 0;
}

为什么输出打印这是常数库。但是如果我在func()的基本版本中删除const,它打印这是非常量派生

Why does the output prints "This is constant base". However if i remove const in the base version of func(), it prints "This is non constant derived"

d-> func ,即使当Base func()是const对吗?

d->func() should call the Derived version right, even when the Base func() is const right ?

推荐答案

 virtual void func() const  //in Base
 virtual void func()        //in Derived

const 部分是实际上是函数签名的一部分,这意味着派生类定义了函数,而不是覆盖基类函数。

const part is actually a part of the function signature, which means the derived class defines a new function rather than overriding the base class function. It is because their signatures don't match.

当删除 const 部分时,它们的签名匹配,然后编译器将 func 的派生类定义视为基类函数的重写版本 func ,因此如果对象的运行时类型为 Derived 类型,则调用派生类函数。这种行为称为运行时多态性。

When you remove the const part, then their signature matches, and then compiler sees the derived class definition of func as overridden version of the base class function func, hence the derived class function is called if the runtime type of the object is Derived type. This behavior is called runtime polymorphism.

这篇关于虚函数const vs虚函数非const的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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