首页 > 解决方案 > 为什么继承在方法内部不起作用?

问题描述

这不会编译:

struct Base
{
    void something( int a ) { }
};
struct Derived : public Base
{
    static void something()
    {
        std::unique_ptr<Derived> pointer = std::make_unique<Derived>();
        pointer->something( 11 );
    }
};

可以修复using Base::something但仍然可以使继承工作,即使在方法内部也能像宣传的那样工作?

标签: c++oopinheritancec++17

解决方案


通过在派生类中为函数使用相同的名称,您可以从基类中隐藏符号。

using您可以通过使用以下语句从基类中提取名称来解决它:

struct Derived : public Base
{
    // Also use the symbol something from the Base class
    using Base::something;

    static void something()
    {
        std::unique_ptr<Derived> pointer = std::make_unique<Derived>();
        pointer->something( 11 );
    }
};

推荐阅读