如果 date
类的 operator+()
成员函数没有返回任何内容,为什么编译器不返回错误。如果我这样做
date d1,d2;
date any = d1 + d2;
然后 d1 + d2
将创建一个临时文件,这个临时文件是用什么初始化的?
date operator+(date d)
{
day += d.day;
month += d.month;
year += d.year;
}
注意:仅供测试。不得用于商业用途或任何用途。
最佳答案
因为它是 operator +()
而不是 operator +=()
,你应该创建一个临时的并返回相同的:
date operator + (const date &d) const
{ // ^^^^ 1 ^^^^^ 2
date temp = *this; // copy current object
...
return temp; // important: -Wall warned you for missing 'return'
}
您还可以看到其他 2 个重要变化:
(1) 传递d
作为const
引用;因为你不需要另一个拷贝
(2) 通过在末尾添加const
使operator +
为const
正确;因为你不会修改this
对象
更新:对于您更新后的问题,这里有一个回答问题的链接。
Why “not all control paths return a value” is warning and not an error?
关于c++ - operator + ( ) 重载的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9092771/