1

Mammal親クラス があります。DogCatLionはサブクラスです。

ベクトルを使用して、すべてのサブクラスをMammalオブジェクトとして保持しています

vector<Mammal> v;

そして、この行を使用して新しいオブジェクトをベクターに追加します。

v.push_back(new Dog(Name, Blue, Owner));

どうやらうまくいきません。Error no instance of overload functionコンパイル中にスローされます。私は C++ を初めて使用するので、親クラスの配列を動的に作成してすべての子オブジェクトを保持する正しい方法がわからない

4

2 に答える 2

6

ブチッパーはすでにあなたに良いアドバイスをしました。ペットの寿命を正しく管理したい場合は、生のポインターの代わりにstd::unique_ptr<>orを使用することを検討してください。std::shared_ptr<>

// the vector owns the pets and kills them, when they are removed
// from the vector
vector<std::unique_ptr<Mamal> > v1

// the vector has shared ownership of the pets. It only kills them,
// when noone else needs them any more
vector<std::shared_ptr<Mamal> > v2

// the vector has no ownership of the pets. It never kills them.
vector<Mamal*> v3

最後のケースでは、他の誰かがペットの死の世話をしなければなりません。ペットにそんなことしたくないですよね?

更新 ああ、言い忘れましたが、新しいものよりも優先するmake_shared()make_unique()emplace_back()代わりに使用する必要がありますpush_back()

v1.emplace_back(new Dog{Name, Blue, Owner});
v1.push_back(make_unique<Dog>(Name, Blue, Owner))

v2.emplace_back(new Dog{Name, Blue, Owner});
v2.push_back(make_shared<Dog>(Name, Blue, Owner))
于 2015-11-06T07:32:53.310 に答える