此警告是由 GCC-13 开始的 G++ 编译器发出的。
Clang++ 17 对这段代码很满意。
MSCV 19 产生类似的警告
(39): 警告 C4263: 'Derived &Derived::operator =(const Derived &)': 成员函数不会重写任何基类虚拟成员函数
(46): 警告 C4264: 'const Parent &Parent::operator =(int &)': 没有可用于基类 'Parent' 的虚拟成员函数的重写;功能被隐藏
(10): 注意:参见 'Parent::operator =' 的声明
(5): 注意:参见“Parent”声明
隐藏操作员也没有帮助。
对我来说,这看起来像是 C++ 标准中的一个缺陷。
#include <iostream>
using namespace std;
struct Parent
{
Parent() = default;
virtual ~Parent() = default;
virtual const Parent & operator=(int &x)
{
x = 0;
return *this;
}
};
struct Derived : public Parent
{
Derived() = default;
virtual ~Derived() = default;
#if (true)
/* Set to false to get rid of the following warning
g++ -o Woverloaded-virtual-test -Wall -Wextra Woverloaded-virtual-test.cpp
or
clang++ -o Woverloaded-virtual-test -Wall -Wextra Woverloaded-virtual-test.cpp
main.cpp:18:28: warning: ‘virtual const Parent& Parent::operator=(int&)’ was hidden [-Woverloaded-virtual=]
18 | virtual const Parent & operator=(int &x)
| ^~~~~~~~
main.cpp:48:24: note: by ‘constexpr Derived& Derived::operator=(const Derived&)’
48 | constexpr Derived& operator=(const Derived&) = delete;
| ^~~~~~~~
*/
#else
virtual const Parent & operator=(int &x)
{
return Parent::operator=(x);
}
#endif
constexpr Derived& operator=(const Derived&) = delete;
void method(int &x)
{
x *= 2;
return;
}
};
int main()
{
cout<<"Hello World";
Derived D;
int x = 2;
D.method(x);
return x;
}
Derived& operator=(const Derived&) = delete
不具有使该功能仿佛从未存在过的效果。
这个
= delete
声明仍然具有隐藏基类函数的作用。
我们可以通过使基类版本在子类中再次可见来修复此错误:
constexpr Derived& operator=(const Derived&) = delete;
using Parent::operator=;