gpt4 book ai didi

c++ 用c++重载虚函数警告?

转载 作者:IT老高 更新时间:2023-10-28 12:14:50 27 4
gpt4 key购买 nike

clang 在编译以下代码时发出警告:

struct Base
{
virtual void * get(char* e);
// virtual void * get(char* e, int index);
};

struct Derived: public Base {
virtual void * get(char* e, int index);
};

警告是:

warning: 'Derived::get' hides overloaded virtual function [-Woverloaded-virtual]

(当然需要启用上述警告)。

我不明白为什么。请注意,取消注释 Base 中的相同声明会关闭警告。我的理解是,由于两个 get() 函数的签名不同,所以无法隐藏。

clang 对吗?为什么?

请注意,这是在 MacOS X 上运行的最新版本的 Xcode。

clang --version
Apple LLVM version 5.0 (clang-500.1.74) (based on LLVM 3.3svn)

更新:与 Xcode 4.6.3 的行为相同。

最佳答案

此警告用于防止在打算覆盖时意外隐藏重载。考虑一个稍微不同的例子:

struct chart; // let's pretend this exists
struct Base
{
virtual void* get(char* e);
};

struct Derived: public Base {
virtual void* get(chart* e); // typo, we wanted to override the same function
};

因为它是一个警告,它并不一定意味着它是一个错误,但它可能表明一个错误。通常,此类警告有一种方法可以通过更明确地关闭它们并让编译器知道您确实打算编写您所写的内容。我相信在这种情况下,您可以执行以下操作:

struct Derived: public Base {
using Base::get; // tell the compiler we want both the get from Base and ours
virtual void * get(char* e, int index);
};

关于c++ 用c++重载虚函数警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18515183/

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