24

处理 C++ 的 hides overloaded virtual function 警告

 2 years ago
source link: https://zhiqiang.org/coding/remove-hides-overloaded-virtual-function-warning.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

处理 C++ 的 hides overloaded virtual function 警告

作者: 张志强

, 发表于 2021-08-12

, 共 870 字 , 共阅读 10 次

遇到这个问题,后来找到https://stackoverflow.com/questions/18515183/c-overloaded-virtual-function-warning-by-clang

下面这段代码

struct Base
{
    virtual void * get(char* e); 
};

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

会爆出一个警告:

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

这个警告是为了防止误写:

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);
};

根据需要,可以把 Base 的函数直接隐藏掉:

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

Q. E. D.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK