メンバー関数で動的配列を作成しようとしていますが、関数を呼び出すたびに新しい動的配列が作成されるようです。とにかくメンバ関数内で動的配列を作成して、それ自体をリメイクしませんか?クラスメンバー関数で動的配列を作成する
class predator
{
private:
string name;
string species;
protected:
string *list;
public:
predator(string theSpecies);
void killsRecorded(string kills); // add a new kill to the end of the predator's list of kills
string *killsList(); // return a pointer to the array of all kills by this predator
int noOfTotalKills(); // how many kills have been recorded
int k;
static int n;
};
//The header file
void predator::killsRecorded(string kills)
{
k = 0;
list = new string[5];
*(list + k) = kills;
k = n++;
cout<< k<< endl;
}
string* predator::killsList()
{
//cout<< (sizeof(list)/sizeof(list[0]))<< endl;
for(int i=0; i<5; i++)
{
cout<< *(list + i)<< endl;
}
}
上記は、私は私のメインの中にいることをしようとすると、ボイドkillsRecordedは(文字列は殺す)、しかし、私の配列にキルを追加する必要があり、私のクラスとヘッダファイルです。
predator *prey;
prey = new predator("Cheetah");
prey->killsRecorded("Mouse");
prey->KillsRecorded("Donkey");
prey->killsList();
ではなく
Created a hunter that is a Cheetah
0
1
Donkey
*BLANK LINE
*BLANK LINE
*BLANK LINE
*BLANK LINE
を出力し、マウスは、第二の最初の行とロバであるべきです。私は何か間違っているのですか?また、私はベクトルを使用することはできません、それは割り当てのためです。
は '文字列*李を使用していません「ベクトルリスト」を使用してください。あなたは 'n'や 'k'は必要ありません。 'cout << list [i] << endl;' –
dgsomerton
'recordKills'関数ではなく、コンストラクタで' list'を初期化してください。 – PcAF
1.配列をメンバ変数にする2.配列をベクトルに変更 –