腾讯笔试--处理 C++ 的 hides overloaded virtual function 警告

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


腾讯笔试题目中遇到的问题。

下面这段代码

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

解决办法总结: 要是使用同时使用基类的方法, 要么将基类的方法在之类的private权限修饰符下隐藏掉。

猜你喜欢

转载自blog.csdn.net/qq_40669895/article/details/143246344