【问题标题】:C++ inheritance overloads functions with different parameters [duplicate]C ++继承重载具有不同参数的函数[重复]
【发布时间】:2020-07-24 15:27:19
【问题描述】:

我正在开发一个使用类继承并且在基类和派生类中都需要大量重载的项目,我已经简化了代码,但我不想不必要地复制和粘贴,因为这应该是继承是为了。

#include <iostream>

class Base
{
public:
    Base() = default;

    //base const char* overload
    void foo(const char* message)
    {
        std::cout << message << std::endl;
    }
    //other overloads ...
};
class Derived : public Base
{
public:
    Derived() = default;

    //derived int overload
    void foo(int number)
    {
        std::cout << number << std::endl;
    }
};

int main()
{
    Derived b;
    b.foo(10); //derived overload works
    b.foo("hi"); //causes error, acts as if not being inherited from Base class
    return 0;
}

【问题讨论】:

标签: c++ polymorphism overloading using-declaration name-hiding


【解决方案1】:

您可以在派生类中使用 using 声明,如

using Base::foo;

使基类中声明的重载函数 foo 在派生类中可见。

这是插入 using 声明的程序。

#include <iostream>

class Base
{
public:
    Base() = default;

    //base const char* overload
    void foo(const char* message)
    {
        std::cout << message << std::endl;
    }
    //other overloads ...
};
class Derived : public Base
{
public:
    Derived() = default;

    using Base::foo;
    //derived int overload
    void foo(int number)
    {
        std::cout << number << std::endl;
    }
};

int main()
{
    Derived b;
    b.foo(10); //derived overload works
    b.foo("hi"); //causes error, acts as if not being inherited from Base class
    return 0;
}

程序输出是

10
hi

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-30
    相关资源
    最近更新 更多