2016-10-13 12 views
0

3つのクラスの要素の配列を別のクラスに初期化しようとしています(ベクトルと初期化子のリストを使うことができますが、道)とのは、私は元のために、このコードをしたとしましょう:C++の配列クラスコンストラクタについての簡単な説明

class A{ 
// CODE HERE, doesn't really matter 
} 

、その後

class B{ 

string name; 
A array[3]; <-- here's the point. I want array of 3 members of class A 

public: 

B(string name_, A a, A b, A c) : name(name_), array[0](a), array[1](b), array[2](c){} // Here's the problem. I can't initialize this way, it always give me some sort of error and array isn't recognized as a class variable (no color in the compiler like 'name' for ex shows and it should be). 

} 

何らかの理由で、私はプロトタイプで初期化しないと、ちょうどこのような関数の中にそれを行う場合 - > array [0] = aなどで動作します。しかし、私は上記のようにインラインで行う方法を知りたいです。

答えて

1

あなたはこのようなあなたのアレイのためのブレース初期化リストを使用することができますあなたの例から、単にタイプミス固定した後:

class A{ 
// CODE HERE, doesn't really matter 
}; 


class B{ 

string name; 
A array[3]; // <-- here's the point. I want array of 3 members of class A 

public: 

B(string name_, A a, A b, A c) : name(name_), array{a,b,c} {} 
               // ^^^^^^^ 

}; 

See Live Demo

この時点でインデックスによる逆参照はできません。

1

あなたはこのようにそれを行うことができますでのC++ 11

class B{ 
    string name; 
    A array[3]; 

public: 

    B(string name_, A a, A b, A c) 
     : name(name_), 
     , array{a, b, c} 
    { 
    } 
}; 
関連する問題