我可以实现一个 Base,其 Derived 在 Derived::Derived 作用域之后自动调用 Base::sanitycheck 吗?

问题描述 投票:0回答:1

如何通过适当修改除

Derived::Derived()
之外的任何代码来实现所需的输出?

#include<iostream>
std::ostream& o=std::cout;

struct Base{
    void sanitycheck(){ o<<"base checks\n"; }
    Base(){ o<<"make base\n"; }
};

// code of struct Derived shall remain unaltered
struct Derived: Base{
    Derived(){ o<<"make derived\n"; }
};

// Dummy might help?
struct Dummy{
    Base& base;
    Dummy(Base& base):base(base){}
    ~Dummy(){ base.sanitycheck(); }
};

int main(){
    Derived x;
    /* desired output:
    make base
    make derived
    base checks     // <-- missing piece
    */
}

背景:基地位于图书馆内。派生是用户提供的。健全性检查可以帮助减少用户错误。

c++ inheritance constructor
1个回答
0
投票

如果我正确理解你的要求,你只需要

Derived x;
Dummy x_dummy{x};   // Missing line

查看演示

© www.soinside.com 2019 - 2024. All rights reserved.