【问题标题】:Why inheritance doesn’t work inside methods? [duplicate]为什么继承在方法内部不起作用? [复制]
【发布时间】:2021-10-03 07:50:57
【问题描述】:

这不会编译:

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 进行修复,但即使在方法内部也可以使继承工作如宣传的那样?

【问题讨论】:

  • 注意Derived() 中的函数是staticBase 中的函数不是,所以它不会覆盖它。另外,即使Derived 中的函数不是静态的,Base 中的函数也需要声明为virtual 才能被覆盖
  • 我认为问题在于为什么不能从Derived:::something() 自动访问Base::something(int)
  • 什么是“广告”?还有谁?

标签: c++ oop inheritance c++17


【解决方案1】:

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

您可以通过使用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 );
    }
};

【讨论】:

    【解决方案2】:

    我不确定您要完成什么。我添加了virtual,并更改了Derived something 类函数的名称,并放入了两个变体。一种变体通过虚继承调用,另一种直接调用基类成员函数。

    #include <iostream>
    
    using std::cout;
    
    namespace {
    
    struct Base {
        virtual ~Base();
        virtual void something(int a) { std::cout << "Base a:" << a << "\n"; }
    };
    
    Base::~Base() = default;
    
    struct Derived : Base {
        void something(int b) override { std::cout << "Derived b:" << b << "\n"; }
        static void action() {
            std::unique_ptr<Derived> pointer = std::make_unique<Derived>();
            pointer->something(11);
        }
        static void other_action() {
            std::unique_ptr<Derived> pointer = std::make_unique<Derived>();
            pointer->Base::something(11);
        }
    };
    
    } // anon
    
    int main() {
        Derived::action();
        Derived::other_action();
    }
    

    【讨论】:

      猜你喜欢
      • 2019-10-21
      • 1970-01-01
      • 2015-01-19
      • 1970-01-01
      • 1970-01-01
      • 2015-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多