簡體   English   中英

運算符優先級更改

[英]Operator precedence change

下面的代碼用於在VS2008上構建OK,但在VS2013上則抱怨。 在g ++中可以。

#include <sstream>
int main()
{
    int a = 2, b = 5;
    std::ostringstream oss;

    oss << a == 0 ? a : b;
}

錯誤消息是

1>u:\precedence\precedence.cpp(7): error C2678: binary '==' : no operator found which takes a left-hand operand of type 'std::basic_ostream<char,std::char_traits<char>>' (or there is no acceptable conversion)
1>          c:\program files\microsoft visual studio 12.0\vc\include\exception(497): could be 'bool std::operator ==(const std::exception_ptr &,const std::exception_ptr &)' [found using argument-dependent lookup]
1>          c:\program files\microsoft visual studio 12.0\vc\include\exception(502): or       'bool std::operator ==(std::nullptr_t,const std::exception_ptr &)' [found using argument-dependent lookup]
1>          c:\program files\microsoft visual studio 12.0\vc\include\exception(507): or       'bool std::operator ==(const std::exception_ptr &,std::nullptr_t)' [found using argument-dependent lookup]
1>          c:\program files\microsoft visual studio 12.0\vc\include\system_error(402): or       'bool std::operator ==(const std::error_code &,const std::error_condition &) throw()' [found using argument-dependent lookup]
1>          c:\program files\microsoft visual studio 12.0\vc\include\system_error(410): or       'bool std::operator ==(const std::error_condition &,const std::error_code &) throw()' [found using argument-dependent lookup]
1>          while trying to match the argument list '(std::basic_ostream<char,std::char_traits<char>>, int)'

如果將輸出語句更改為,則在兩個版本上均適用

    oss << (a == 0? a: b);

如果不使用常量,我可以在VS2008中強制執行其他錯誤:

int zero = 0;
oss << a == zero? a: b;

只是想知道為什么不使用常量時會出錯。

使用-Wall使用g ++ 編輯 Managed以獲得警告。

在所有情況下,由於優先級,編譯器看到的表達式為:

((oss << a) == 0) ? a : b;

現在oss << a返回oss 如何將oss與0進行比較? 它具有一個隱式轉換運算operator void *

VS2013大概用C ++ 11的explicit operator bool代替了(其全部要點是這樣就不會出現這些難以發現的錯誤)。 據我所知,libstdc ++尚未完成此替換。 它必須符合C ++ 11。

現在為什么不zero編譯? zero不是空指針常量,而是0 因此,可以將后者與operator void *返回的指針進行比較。

在任何情況下,解決此問題以便與任何符合要求的實現一起正常工作的簡單方法是添加括號:

oss << (a == 0 ? a : b);

看來編譯器在解釋它時有所不同。

基於該錯誤,我懷疑編譯器正在解釋這樣的代碼行

(oss << a) == 0 ? a : b;

因此,當您放入括號時,便不再有任何方式可以這樣解釋它,並且您得到了預期的結果。 我懷疑這也會起作用。

oss << (a == 0) ? a : b;

暫無
暫無

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

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