2

私は次の問題に遭遇しました。これは、C++の動作についてほとんど知らないことを私に証明しました。

純粋仮想関数を持つ基本クラスを使用します

class Base
    ...

および型の派生クラス

class Derived : public Base{
private:
  Foo* f1;
 ...

どちらにも代入演算子が実装されています。特に、Derivedの代入演算子は、f1のデータをコピーします。私のコードでは、Derivedクラスの2つの新しいインスタンスを作成します

Base* d1 = new Derived();
Base* d2 = new Derived();

ここで代入演算子を呼び出すと

*d1 = *d2;

Derivedの代入演算子は呼び出されず、f1のデータはコピーされません!私がする場合にのみ機能します

*dynamic_cast<Derived*>(d1) = *dynamic_cast<Derived*>(d2);

代入演算子がオーバーロードされない理由を誰かが説明できますか?

ありがとう!

4

3 に答える 3

4

It's hard to say without seeing the relevant code. Here's an example that works:

#include <iostream>

using namespace std;

class A {
  public:
    virtual A& operator=(A& a) {}
};

class B : public A {
  public:
    B& operator=(A& a) { cout << "B" << endl; }
};

int main() {
  A* foo = new B();
  A* bar = new B();
  *foo = *bar;
  return 0;
}

This will print B when run.

Things that you might be doing wrong:

  1. You might have forgotten to make operator= virtual in the base class.
  2. You might have given the child's class operator= as signature that's more restrictive than that of the parent's operator=, so you're not actually overriding the parent's definition. For example if you change B& operator=(A& a) { cout << "B" << endl; } to B& operator=(B& a) { cout << "B" << endl; } in the example above, it will no longer print B.
于 2010-09-16T23:35:29.220 に答える
3

受け入れられた答えについて、別の見方があります。これは基本的にMore Effetive C++項目 33 です。したがって、受け入れられた解決策が機能するとしても、代入演算子を仮想化することに伴う危険性を明らかにすることが重要だと思います。

class Animal {
public:
    virtual Animal& operator=(const Animal& rhs);
};

class Lizard: public Animal {
public:
    virtual Lizard& operator=(const Animal& rhs);
};

class Chicken: public Animal {
public:
    virtual Chicken& operator=(const Animal& rhs);
};

int main(){
    Lizard l;
    Chicken c;

    Animal *pL = &l;
    Animal *pC = &c;

    *pL = *pC;             // assigns chicken to a lizard.
}
于 2010-09-17T04:28:04.457 に答える
1

仮想が機能するには、同じ署名が必要です。したがって、基本クラスのパラメーターで機能しているパラメーターと一致しないクラスのパラメーターでoperator=機能している場合。const Derived&Derivedconst Base&

これは、ポリモーフィズムを実現できることを意味しますが、operator=(const Base&)そのためには派生クラスに が必要です。

于 2010-09-16T23:29:25.303 に答える