gpt4 book ai didi

c++ - 初始化动态字符串数组 (C++)

转载 作者:行者123 更新时间:2023-11-30 01:59:14 24 4
gpt4 key购买 nike

我正在为动态字符串数组创建容器类进行分配。我知道使用 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] ();
}

关于c++ - 初始化动态字符串数组 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16487486/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com