簡體   English   中英

C++ 中的運算符重載真的期望返回值嗎?

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

我不明白以下片段之間的區別。 一個有返回值,另一個沒有。 真正的區別是什么? 什么時候用什么? 期待收到您的答復。

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
}

最后一個是轉換運算符,因此暗示它返回一個float - 您將值轉換為這種類型。

至於operator< ,它具有返回類型,因為您實際上可以隨心所欲地制作它。 例如,C++ 標准庫流的operator<<執行 I/O 而不是邏輯移位。

實際上,每當我們重載運算符時,其開發人員都有責任保持運算符行為與語言中提到的相同。 當我們開發一段可供成千上萬用戶使用的代碼時,每個人都沒有時間檢查我們代碼的實現。

最小驚訝原則意味着系統的一個組件應該以大多數用戶期望的方式運行; 該行為不應讓用戶感到驚訝或驚訝。

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