gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 18:22:02 26 4
gpt4 key购买 nike

考虑:

#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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com