0

問題はC++についてです。私には3つのクラスがあります。1つMovieMaker目は抽象、2つ目は最初のクラスActorから派生し、3つ目は「Director」という名前は。から派生しActorます。ActorとDirectorの両方のインスタンスを保持できる配列を作成したいと思います。どうやってやるの?

4

2 に答える 2

3

MovieMakerポインタの配列を作成します。派生クラスへのポインタを保持できます。この手法はポリモーフィズムと呼ばれます-ここに素晴らしいチュートリアルがあります:

http://www.cplusplus.com/doc/tutorial/polymorphism/

于 2013-03-13T13:12:09.913 に答える
3

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.

于 2013-03-13T13:16:09.493 に答える