簡體   English   中英

a + b和運算符+(a,b)之間的區別

[英]Difference between a+b and operator+(a,b)

考慮以下程序:

#include<functional>

typedef std::function< int( int ) > F;

F operator+( F, F )
{
    return F();
}

int f( int x ) { return x; }

int main()
{
    operator+(f,f); // ok
    f+f; // error: invalid operands to binary expression
}

為什么最后一行f+f; 無法編譯? 為什么它與operator+(f,f); 對標准的引用將不勝感激。

f的類型是內置類型。 內置類型的對象上的操作永遠不會考慮用戶定義的運算符。 調用operator+(f, f)顯式強制執行兩次轉換,除非將其強制執行,否則不會發生。 相關條款是13.3.1.2 [over.match.oper]第1段:

如果表達式中沒有運算符的操作數具有類或枚舉的類型,則假定該運算符是內置運算符,並根據第5章進行解釋。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM