簡體   English   中英

返回類型為?:operator,以及C ++ Primer中的短語

[英]Return type of ?: operator, and phrasing in C++ Primer

我閱讀這篇文章來概述條件運算符返回的類型和值類別: 返回類型'?:'(三元條件運算符)

這幾乎解答了我的問題,除了用C ++ Primer中的措辭描述同樣的事情讓我有些困惑。

“如果兩個表達式都是左值或者它們轉換為公共左值類型 ,則條件運算符的結果是左值 。否則結果是右值。”

粗體鑽頭讓我失望。 例如,這會向我建議

int main(){

    int y = 2;
    char z = 3;

    ((50<60) ? y : z) = 3;
}

沒問題,因為y和z都可以轉換為int(嗯,z將是轉換后的那個),這是一個左值類型(右?),因此條件運算符會給左值作為其值類別。 然而,這個編碼器不能編譯,因為它實際上給出了一個rvalue。 任何人都可以提供一個粗體位提到的例外情況的例子,所以我可以理解它試圖制作什么點?

我的理解似乎是:如果表達式是相同類型的左值,則返回該類型的左值。 否則返回rvalue(由某些編譯器確定的類型)。

如果z轉換為int ,則已應用左值到右值的轉換,結果是prvalue,而不是左值。

?:一個例子?:其中兩個操作數具有不同的類型,但結果是左值,是一個是const限定而另一個不是:

const int &f(bool a, int &b, const int &c) {
  // b has type int, c has type const int, the result is an lvalue of type const int
  return a ? b : c;
}

另一個例子是其中一個是具有自定義轉換運算符的類:

struct S {
  operator int&();
};
int &f(bool a, int &b, S &c) {
  // b has type int, c has type S, the result is an lvalue of type int
  // if a is false, c's conversion operator is called
  return a ? b : c;
}

暫無
暫無

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

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