覆盖非const虚方法是否会隐藏const重载? [英] Does overriding a non-const virtual method hide a const overload?

查看:107
本文介绍了覆盖非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 :


首先,[编译器]查看
立即范围,在本例中为C类的
范围,并使一个
的列表,它可以找到名为f的
的所有函数(无论它们是否可以访问
,或者甚至采用正确的
参数数量)。 只有当
没有这样做时才将
向外继续到下一个封闭的
范围
[...]

所以是的, 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重载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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