本文介绍了覆盖非const虚方法是否会隐藏const重载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑:

#include <iostream>

using namespace std;

struct A {
  virtual void f() { cout << "A::f" << endl; }
  virtual void f() const { cout << "A::f const" << endl; }
};

struct B : public A {};

struct C : public A {
   virtual void f() { cout << "C::f" << endl; }
};


int main()
{
   const B b;
   b.f();   // prints "A::f const"

   const C c;
   c.f();
   // Compile-time error: passing ‘const C’ as ‘this’ argument of
   //   ‘virtual void C::f()’ discards qualifiers
}

(我正在使用GCC。)

(I'm using GCC.)

所以看来f()的const版本隐藏在C中。这对我来说很有意义,但它是否由标准规定?

So it seems that the const version of f() gets hidden in C. This makes a lot of sense to me, but is it mandated by the standard?

推荐答案

我将(再次)链接这个伟大的:

I will (once more) link this great article :

所以是的, const 版本的 f 是隐藏,这是完全正常的。正如Simone所指出的,您可以使用使用语句将 A :: f 带入 C 范围。

So yes, the const version of f is hidden, and that's perfectly normal. As pointed out by Simone, you can use a using statement to bring A::f in C scope.

这篇关于覆盖非const虚方法是否会隐藏const重载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 07:37
查看更多