所以我为我在课堂上写的 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)