文字列の動的配列のコンテナ クラスを作成する割り当てに取り組んでいます。std::vector を使用すると、はるかに簡単/より適切に実行できることはわかっていますが、それは重要ではありません。コンストラクターで配列を初期化する正しい方法を見つけるのに問題があります。以下のように、変数 lineArray が使用されていないことをコンパイラからまだ警告されています。プログラムは、lineArray が使用されていないという警告とともにコンパイルされ、実行時にハングします。
MyBag::MyBag()
{
nLines = 0;
std::string lineArray = new std::string[0] ();
}
void MyBag::ResizeArray(int newLength)
{
std::string *newArray = new std::string[newLength];
//create new array with new length
for (int nIndex=0; nIndex < nLines; nIndex++)
{
newArray[nIndex] = lineArray[nIndex];
//copy the old array into the new array
}
delete[] lineArray; //delete the old array
lineArray = newArray; //point the old array to the new array
nLines = newLength; //set new array size
}
void MyBag::add(std::string line)
{
ResizeArray(nLines+1); //add one to the array size
lineArray[nLines] = line; //add the new line to the now extended array
nLines++;
}