让我们看一下这段代码:
#include <boost/asio/impl/error.ipp>
struct Type : public boost::system::error_category
{
const char * name() const noexcept override
{
return nullptr;
}
std::string message(int) const override
{
return {};
}
};
正如我们所见,它编译时没有警告。
现在让我们创建相同的代码(方法原型是从 boost 中一对一复制的):
#include <string>
struct Base
{
virtual std::string message(int) const = 0;
virtual char const * message(int, char *, std::size_t) const noexcept
{
return nullptr;
}
};
struct Deriv : Base
{
std::string message(int) const
{
return {};
}
};
突然,编译器开始谈论隐藏该方法。这是什么? GCC 编译器错误?因为例如 Clang 在这种情况下不会发出警告。
也许这是对错误消息的误解?
如果您的类
Deriv
仅定义了Base中重载方法中的一种方法,则所有其他重载都会被隐藏,即使它们是虚拟的。对我来说,警告似乎是正确的!
简化示例:
struct Base
{
virtual void f1() { std::cout << __PRETTY_FUNCTION__ << std::endl; }
virtual void f1( int i) { std::cout << __PRETTY_FUNCTION__ << std::endl; }
};
struct Deriv : Base
{
// using Base::f1; // << add this line to get f1( int ) reachable
void f1() override )
{
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
};
int main()
{
Deriv d;
d.f1();
d.f1(1);
}
这不仅会发出警告,还会引发错误,因为无法访问
f1()
!
您只需添加
using Base::f1; into
Deriv` 即可将所有其他重载添加到派生类中。