1

class ROmethod を持つ親がいvoid setup(const int* p)ます。class RW非定数ポインターのみを許可する同じメソッドを持つ子が必要です。

で 2 つのメソッドを作成しclass RO、 でそれらの 1 つを許可しないことでそれを行いclass RWます。

class RO
{
public:
    void setup(int* p) { DO SMTH }
    virtual void setup (const int* p) { RO::setup( const_cast<int*>(p) ); }

    // the rest...
    void read() const;
};

class RW : public RO
{
public:
    virtual void setup (const int* p) { throw SMTH }

    // the rest...
    void write();
};

RW::setup可能であれば、コンパイル時に許可しないようにしたいと思います。すなわち、

const int* p;

RO* ro = new RW;
ro->setup(p);        // Throw at run time, since it can be unknown
                     // at compile time that ro points to RW and not to RO.

RW* rw = new RW;
rw->f(p);            // Disallow this at compile time, since it is
                     // known at compile time that rw points to RW.

それを行う方法はありますか?

4

2 に答える 2

2

パブリック継承の代わりにプライベートを使用します。usingキーワードを使用して、親クラスのメソッドを子クラスで使用できるようにします。

パブリック継承は、親クラス オブジェクトを使用する誰かが子クラス オブジェクトを使用する可能性がある状況を対象としています (詳細については、 Liskov 置換原則を調べてください)。あなたの要件はそれを破っているので、公開継承には当てはまりません。

于 2013-06-25T21:43:16.317 に答える