C++ 虚函数 const 与虚函数非常量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9488168/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 12:53:31  来源:igfitidea点击:

virtual function const vs virtual function non-const

c++

提问by vamsi

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;
}

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"

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

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

d->func() 应该正确调用派生版本,即使 Base func() 是 const 对吗?

回答by Nawaz

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

constpart is actually a partof the function signature, which means the derived class defines a newfunction rather than overridingthe base class function. It is because their signatures don't match.

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

When you remove the constpart, then their signature matches, and then compiler sees the derived class definition of funcas overridden versionof the base class function func, hence the derived class function is called if the runtime type of the object is Derivedtype. This behavior is called runtime polymorphism.

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

回答by stinky472

virtual void func()is actually of a different signature than virtual void func() const. Thus you didn't override your original, read-only base function. You ended up creating a new virtual function instead in Derived.

virtual void func()实际上与virtual void func() const. 因此,您没有覆盖原始的只读基本函数。您最终在 Derived 中创建了一个新的虚函数。

You can also learn more about this if you ever try to create pointers to member functions (PTMFs), but that's a rare necessity (might be good for study or practice, however).

如果您曾经尝试创建指向成员函数 (PTMF) 的指针,您也可以了解更多相关信息,但这是一种罕见的必要性(然而,这可能对学习或练习有益)。

The override keyword in C++11 is particularly handy to help avoid these kinds of mistakes. The compiler would then tell you that your definition of 'func' in derived does not override anything.

C++11 中的 override 关键字对于帮助避免此类错误特别方便。然后编译器会告诉您,您在派生中对 'func' 的定义不会覆盖任何内容。

回答by Oliver Charlesworth

No, because virtual void func()is not an override for virtual void func() const.

不,因为virtual void func()不是virtual void func() const.