Jhe*_*nda 0 c++ vector push-back
//prototype
void Split(char c, vector <MyString> &outputVector) const
//partial code inside split function
// create new MyString object to push into output vector
MyString substr;
substr.mString = newString;
substr.mLength = size;
// push new item
outputVector.push_back(substr);
Run Code Online (Sandbox Code Playgroud)
在我跨过该outputVector.push_back()行之后,mString不保留数据成员.
//I have two constructors
MyString()
{
mString = NULL;
mLength = 0;
}
/*************************************************
* MyList copy constructor
* creates a deep copy of a MyString item
************************************************/
MyString(const MyString ©)
{
mString = new char[copy.mLength];
int i;
for(; i < copy.mLength; i++)
{ mString[i] = copy.mString[i]; }
mString[i] = '\0';
mLength = copy.mLength;
}
Run Code Online (Sandbox Code Playgroud)
您正在使用未初始化的变量,该变量是未定义的行为
int i;
for(; i < copy.mLength; i++)
Run Code Online (Sandbox Code Playgroud)
在这里我们不知道什么i是可以进行的,但最有可能的i是大于copy.mLength我们永远不会进入for循环.为了获得正确的行为设置i为0喜欢
int i = 0;
Run Code Online (Sandbox Code Playgroud)
你有另一个问题
mString[i] = '\0';
Run Code Online (Sandbox Code Playgroud)
当我们到达那条线i == copy.mLength但是数组只有大小时copy.mLength,我们就是一个接一个,因为数组是基于0索引的.您很可能需要将分配更改为
mString = new char[copy.mLength + 1];
Run Code Online (Sandbox Code Playgroud)
为null终止符提供空间.