0
4

3 に答える 3

5

簡単に言えば、できません。配列は C++ では多態的ではありません。これには正当な理由があります。たとえば、What is object slicing?を参照してください。. たとえばarr[i]、コンパイラは各要素の大きさを知る必要があります (アドレス オフセットを計算するため)。一般に、この計算は派生型では正しくありません。

関数テンプレート、またはおそらく (スマート) ポインターの配列/コンテナーの使用を検討します。

于 2012-04-25T11:53:12.333 に答える
1

You can't have an array of objects and then cast it to array of other objects. Think of it, if Vecteur sizeof is 16 and Testable sizeof is 4, how could this even work?

What you want is an array of pointers to objects.

void commencerTest(Testable* testables[], int nTestables)
{
    for (int i=0; i < nTestables; i++)
        testables[i]->afficher();
}

int main()
{
    Testable* vect[10];

    for(int i=0; i<10; i++)
        vect[i] = new Vecteur();

    commencerTest(vect, 10);
}
于 2012-04-25T11:59:52.467 に答える
0

これを試して:

template <typename Type>
  void Testeur::commencerTest(Type *testables, int nTestables, string titre) {

コードは最終的に、配列のサイズがわからないことについて不平を言うでしょう。ポリモーフィズムはポインターを介して機能しますが、他の人が指摘したように配列は機能しません。

別の可能性として、静的配列の型と数値の両方にコンパイル時のポリモーフィズムを使用できます。

template<typename Type, size_t Num>
  void Testeur::commencerTest(Type (&testables)[Num], string titre) {

また、標準ライブラリ コンテナーは優れたソリューションです。

于 2012-04-25T12:05:28.677 に答える