問題はC++についてです。私には3つのクラスがあります。1つMovieMaker
目は抽象、2つ目は最初のクラスActor
から派生し、3つ目は「Director」という名前は。から派生しActor
ます。ActorとDirectorの両方のインスタンスを保持できる配列を作成したいと思います。どうやってやるの?
2 に答える
MovieMaker
ポインタの配列を作成します。派生クラスへのポインタを保持できます。この手法はポリモーフィズムと呼ばれます-ここに素晴らしいチュートリアルがあります:
Create an array of std::shared_ptr<MovieMaker>
, or unique_ptr
. In C++, it is usually a good idea to create a std::vector
instead of a raw array: so std::vector<std::shared_ptr<MovieMaker>> vec
, which you populate like this:
#include <vector>
#include <memory>
// later:
std::vector<std::shared_ptr<MovieMaker>> vec;
vec.push_back( std::make_shared<Actor>() );
vec.push_back( std::make_shared<Director>() );
vec.push_back( std::make_shared<Actor>() );
or, in C++11:
#include <vector>
#include <memory>
// later:
std::vector<std::shared_ptr<MovieMaker>> vec = {
std::make_shared<Actor>(),
std::make_shared<Director>(),
std::make_shared<Actor>(),
};
If you are willing to use boost
, a 3rd party library, there are a few other options.
Alternatively, create an array of boost::variant<Actor,Director>
, which ignores the class hierarchy and simply stores a type-safe union
like construct. boost::variant
is a bit trick to use.
As another alternative, boost::any
can store anything, and you can query it if what it has is what you want.