1

次の点を考慮してください。

// ConsoleApplication1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <string>
#include <iostream>

using namespace std;

class Foo {
public:
    // NVI
    bool method() {
        cout << "Foo::method" << endl;
        return method_impl();
    }

    // Why not do this instead?
    //virtual bool method() final {
    //    cout << "Foo::method" << endl;
    //    return method_impl();
    //}

private:
    virtual bool method_impl() = 0;
};

class Bar : public Foo {
public:
    // What stops someone from doing this hiding the Foo::method identifier?
    // Uncomment the below and see how the console output is instead Bar::method and then method_impl

    //bool method() {
    //    cout << "Bar::method" << endl;
    //    return method_impl();
    //}

private:
    virtual bool method_impl() override {
        return true;
    }
};


int _tmain(int argc, _TCHAR* argv[]) {
    Bar bar = Bar();

    cout << bar.method() << endl;

    return 0;
}

上記のように、Foo クラスは Foo::method() メンバー関数を使用して NVI パターンに従おうとしています。

子クラス (この場合は Bar) が Foo::method() を Bar::method() で隠すのを妨げているのは何ですか? 私はそれを試してみましたが、何もないと思います。Bar::method() のコメントを外すと、コンソール アプリケーションは実際に method() の Bar 実装に移行します。これは完全に理にかなっています。

virtual final を使用して、子クラスでそのメソッドの名前の非表示を禁止しないのはなぜですか? Foo クラスで提供される例。

ありがとう

4

0 に答える 0