1

あなたがこれを持っているとしましょう:

class foo {
public:
  virtual int myFunc() = 0;
  ///...
  virtual bool who()   = 0; // don't want to implement this
};

class bar : public foo {
public:
  int myFunc() {return 3;}
  //...
  bool who() {return true;} // don't want to implement this
};

class clam : public foo {
public:
  int myFunc() {return 4;}
  //...
  bool who() {return false;} // don't want to implement this
};


int main() {

  std::vector<foo*> vec (2, NULL);
  vec[0] = new bar();
  vec[1] = new clam();

  // copy vec and allocate new ptrs as copies of the data pointed to by vec[i]
  std::vector<foo*> vec2 (vec.size(), NULL);
  for ( int i=0; i<vec.size(); ++i ) {

    // obviously not valid expression, but it would be nice if it were this easy
    //vec2[i] = new foo(*vec[i]); 

    // the hard way of copying... is there easier way?
    if (vec[i]->who()) {
      vec2[i] = new bar ( * static_cast<bar* >(vec[i]) ) ;
    } else {
      vec2[i] = new clam( * static_cast<clam*>(vec[i]) );
    }

  }

  return 0;
}

私が望むのは、コンパイラーがブックキーピングを参照し、格納されている *vec[i] の型に従って vec2[i] を割り当て/コピーする簡単な方法です。回避策は、基本的に *vec[i] の型を指定する値を返す仮想関数を作成し、それに基づいて条件付き割り当てを行うことです。

4

3 に答える 3

4

一般的なアプローチは次のようになります。

class foo {
public:
  virtual foo* clone() = 0;
};

class bar : public foo {
public:
  virtual bar* clone() { return new bar(*this); }
};

class clam : public foo {
public:
  virtual clam* clone() { return new clam(*this); }
};
于 2013-07-20T04:43:49.747 に答える
0

これを行う 1 つの方法は、動的キャストを使用して、ここで行うようにオブジェクトの型を決定することです ( Finding the type of an object in C++ )。しかし、最も簡単な方法は、おそらく typeid を使用することです。

(型を決定子として使用する方法を維持したいと仮定すると、そうでなければ、ヨアヒムまたはイゴールをより良い代替手段としてお勧めします:))

于 2013-07-20T04:44:51.790 に答える