派生带/不带参数的基类函数

Derive base class function with/without arguments

本文关键字:基类 类函数 派生 参数      更新时间:2023-10-16

下面的代码有什么问题?

  class B
{
public:
    int test()
    {
        cout<<"B:test()"<<endl;
        return 0;
    }
    int test(int i)
    {
        cout<<"B test(int i)"<<endl;
        return 0;
    }
};
class D: public B
{
public:
    int test(char x) { cout<<"D test"<<endl; return 0; }
};
int main()
{
    D d;
    d.test();
    return 0;
}

问题是名称隐藏。派生类中的函数test() D在基类B隐藏test()的重载,因此表达式中的重载解析不会考虑这些重载:

d.test()

只需添加一个using声明:

class D: public B
{
public:
    using B::test;
//  ^^^^^^^^^^^^^^
    int test(char x) { cout<<"D test"<<endl;}
};

另请注意,基类B中的test()重载应该返回一个int,但它们不返回任何内容。

根据 C++11 标准的第 6.6.3/2 段,从值返回函数的末尾掉下来而不返回任何内容是未定义的行为

这是一个教科书式的隐藏案例

d.test();

将不起作用,因为派生类test(char)隐藏了所有基类函数,如果执行上述操作,则不会调用匹配函数。