我正在分配以创建用于动态字符串数组的容器类。我知道使用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++;
}
http://ideone.com/pxX18m
最佳答案
您在构造函数中使用了一个名为lineArray
的局部变量。您要使用数据成员,例如:
MyBag::MyBag()
{
nLines = 0;
lineArray = new std::string[0] ();
}