c++ - 重写非常量虚方法是否隐藏了常量重载?

标签 c++ inheritance virtual constants name-lookup

考虑:

#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。)

所以 f() 的 const 版本似乎隐藏在 C 中。这对我来说很有意义,但这是标准强制要求的吗?

最佳答案

我将(再次)链接这个很棒的 article :

First, [the compiler] looks in the immediate scope, in this case the scope of class C, and makes a list of all functions it can find that are named f (regardless of whether they're accessible or even take the right number of parameters). Only if it doesn't does it then continue "outward" into the next enclosing scope [...]

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

关于c++ - 重写非常量虚方法是否隐藏了常量重载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4152799/

相关文章:

c++ - 如何从示例 C 程序发送 HTTP post 请求

c++ - 在函数指针内转换 shellcode

java - 有没有办法在匿名类中初始化最终字段?

process - 具体来说,将进程分成页面是什么意思?

C++将 self 传递给 self 神秘

c++ - 使用 Boost 无法解析的外部符号

php - Inherited() 标志 : propertyName vs. storageName

java - 如何使用 Hibernate 将 ORM 转换为其子类?

linux - 使用虚拟服务器作为开发环境是否安全,符号链接(symbolic link)到主机上的文件?

c++ - 如何在满足 if 语句后获取数组的最后一个值