2021-10-14

关于c++ 子类override函数参数列表与返回值类型与父类不一致的报错信息

class base
{
public:
    virtual int operator()(int a) = 0;
};
//子类A与父类的operator()参数列表与返回值类型完全一致,编译通过
class A : public base
{
public:
    virtual int operator()(int a)
    {
        return a;
    }
};
//B与父类的operator()一致,编译通过
class B : public base
{
public:
    virtual int operator()(int c)
    {
        return c;
    }
};
/*
//B与父类返回值类型不一致,报错信息
error: conflicting return type specified for ‘virtual double B::operator()(int)’
说明B的operator()与base的该方法返回值冲突,无法通过编译
class B : public base
{
public:
    virtual double operator()(int c)
    {
        return 0.1;
    }
};
//报错信息:
error: cannot allocate an object of abstract type ‘B’
     base* b = new B;
                   ^
note:   because the following virtual functions are pure within ‘B’:
说明参数列表不一致子类不会override父类该方法,这个从函数重载的角度很好理解,但是父类的该方法是纯虚函数,子类没有override一定会报错
class B : public base
{
public:
    virtual int operator()(double d)
    {
        return 1;
    }
};
*/
int main()
{
    base* a = new A;
    base* b = new B;
    delete a;
    delete b;
    return 0;
}
上一篇:RAID5阵列掉盘显示未初始化---解决过程


下一篇:Effective C++的读书简要笔记