c++ - operator + ( ) 重载的返回值

标签 c++ operator-overloading return-value

如果 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/

相关文章:

c++ - 为 I/O 以外的事物重载移位运算符是否是一个好的设计?

c++ - Operator() 作为 Matrix 类的下标

python - 无返回值的递归反向列表

scala - Scala中的返回码

python-3.x - 查找矩阵的最大值和最小值

c++ - 尝试在 C++ OpenGL 中打印但返回一个整数?

c++ - 如何使用 "get"方法返回类的私有(private) std::unique_ptr 成员

c++ - 静态库文件中的资源 - MFC

c++ - 在 dll 导出函数中使用 std::vector 的含义

c++ - 使用友元运算符<<的编译器错误