我不明白以下片段之间的区别。一个有返回值,另一个没有。真正的区别是什么?什么时候用什么?期待收到您的答复。
bool Distance::operator < (Distance d2) const
{
float bf1 = feet + inches/12;
float bf2 = d2.feet + d2.inches/12;
return (bf1 < bf2) ? true : false;
}
Run Code Online (Sandbox Code Playgroud)
operator float() const //conversion operator
{ //converts Distance to meters
float fracfeet = inches/12; //convert the inches
fracfeet += static_cast<float>(feet); //add the feet
return fracfeet/MTF; //convert to meters
}
Run Code Online (Sandbox Code Playgroud)
最后一个是转换运算符,因此暗示它返回一个float- 您将您的值转换为这种类型。
至于operator<,它具有返回类型,因为您实际上可以随心所欲地制作它。例如,operator<<对于 C++ 标准库流,执行 I/O 而不是逻辑移位。