因此,我为我在课堂上编写的ADT编写了这两个版本的重载赋值运算符。当我将它们与同一个ADT的重载的ostream <

void Text::operator= (const Text &other) {
if (this != &other) {
    delete [] buffer;
    bufferSize = other.bufferSize;
    buffer = new char[bufferSize + 1];
    strcpy(buffer, other.buffer);
    }
}

 void Text::operator= (const Text &other) {
if (this != &other) {
    delete [] buffer;
    bufferSize = other.bufferSize;
    buffer = new char[bufferSize + 1];
    for (int i = 0; i < bufferSize; i++) {
         buffer[i] = other.buffer[i];
     }
}


这是我超载的ostream <
ostream & operator << (ostream &output, const Text &outputText) {
output << outputText.buffer;
return output;
}


出现这种差异是这样的:

第一个输出:Hey Jude

第二个输出:Hey Jude(random garbage)

最佳答案

第二个代码段未附加终止的空终止符,因此出现了垃圾(strcpy()复制了终止的空终止符)。您需要在for循环后显式添加空终止符:

buffer[bufferSize] = 0;

09-06 22:55