简体   繁体   English

C++ 中的运算符重载真的期望返回值吗?

[英]does operator overloading in C++ really expect a return value?

I don't understand the difference between the following snippets.我不明白以下片段之间的区别。 One has a return value and the other doesn't.一个有返回值,另一个没有。 What really is the difference?真正的区别是什么? When to use what?什么时候用什么? Looking forward to receiving your answers.期待收到您的答复。

bool Distance::operator < (Distance d2) const 
{
    float bf1 = feet + inches/12;
    float bf2 = d2.feet + d2.inches/12;
    return (bf1 < bf2) ? true : false;
}
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
}

The last one is a conversion operator, so it is implied that it returns a float - you convert your value to this type.最后一个是转换运算符,因此暗示它返回一个float - 您将值转换为这种类型。

As for operator< , it has return type because you can actually make it whatever you like.至于operator< ,它具有返回类型,因为您实际上可以随心所欲地制作它。 For instance, operator<< for C++ standard library streams do I/O instead of logical shifting.例如,C++ 标准库流的operator<<执行 I/O 而不是逻辑移位。

Actually, whenever we overload the operator its developer responsibility to keep operator behavior the same as mentioned in language.实际上,每当我们重载运算符时,其开发人员都有责任保持运算符行为与语言中提到的相同。 As we develop the piece of code that can be used by thousands of users, each doesn't have time to check the implementation of our code.当我们开发一段可供成千上万用户使用的代码时,每个人都没有时间检查我们代码的实现。

The principle of least astonishment means that a component of a system should behave in a way that most users will expect it to behave;最小惊讶原则意味着系统的一个组件应该以大多数用户期望的方式运行; the behavior should not astonish or surprise users.该行为不应让用户感到惊讶或惊讶。

https://www.modernescpp.com/index.php/c-core-guidelines-rules-for-overloading-and-overload-operators https://www.modernescpp.com/index.php/c-core-guidelines-rules-for-overloading-and-overload-operators

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM