所以我将两个
Word
对象的重载加法称为
Word w;
w + w;
声明和定义是:
Sentence operator+(const Word&) const;
Sentence Word::operator+(const Word& rightWord) const {
std::cout <<"Entering function Word::operator+(const Word&)."<< std::endl;
std::cout <<"Leaving function Word::operator+(const Word&).\n"<< std::endl;
}
执行
w + w
后,一个 Sentence
对象被销毁(我重载了析构函数以打印到标准输出)我之前创建了一个句子对象,但我认为这不会影响它。我不明白一个句子对象在没有被构造的情况下是如何被破坏的(我也重载了默认构造函数)。
我也不明白为什么会创建它,因为我什至没有真正归还它。我通过 gdb 运行它,当它退出加法函数时,它肯定会调用句子的析构函数。
如果非 void
函数没有返回任何内容,则为
未定义行为。您观察到的所有效果都不是由 C++ 语言定义的,而是特定于您的编译器和/或只是随机的。
事实上,你的编译器应该针对这段代码发出警告消息,甚至是错误。例如,以下使用 Visual C++ 2015 生成
error C4716: 'Word::operator+': must return a value
:
#include <iostream>
struct Sentence {};
struct Word {
Sentence operator+(const Word&) const;
};
Sentence Word::operator+(const Word& rightWord) const{
std::cout<<"Entering function Word::operator+(const Word&)."<<std::endl;
std::cout<<"Leaving function Word::operator+(const Word&).\n"<<std::endl;
} // error C4716
int main() {
}