簡體   English   中英

C ++中一個怪異的表達式-這是什么意思?

[英]A weird expression in c++ - what does this mean?

我已經看過這段代碼,可以找到矩陣的次要部分:

RegMatrix RegMatrix::Minor(const int row, const int col)const{
  //printf("minor(row=%i, col=%i), rows=%i, cols=%i\n", row, col, rows, cols);
 assert((row >= 0) && (row < numRow) && (col >= 0) && (col < numCol));

 RegMatrix result(numRow-1,numCol-1);

 // copy the content of the matrix to the minor, except the selected
    for (int r = 0; r < (numRow - (row >= numRow)); r++){
  for (int c = 0; c < (numCol - (col > numCol)); c++){
   //printf("r=%i, c=%i, value=%f, rr=%i, cc=%i \n", r, c, p[r-1][c-1], r - (r > row), c - (c > col));
   result.setElement(r - (r > row), c - (c > col),_matrix[r-1][c-1]);
  }
 }
     return result;
}

這是我第一次遇到這樣的代碼行:r <(numRow-(row> = numRow))。

這是什么意思?

(row >= numRow)是一個布爾表達式。 如果沒有重載operator>= ,則如果row大於或等於numRow ,則應該為true ,否則為false 當將此布爾值轉換為整數進行減法運算時,如果為true,則將變為1,否則為0。

(row >= numRow)是一個布爾表達式,當像這樣使用時,將其轉換為一個inttrue變為1false變為0

一種更清晰的表達方式可能是:

r < (row >= numRow ? numRow - 1 : numRow)

row >= numRow將返回布爾值true或false,即隱式轉換為整數01 所以這樣做基本上與以下內容相同:

r < (numRow - (row >= numRow ? 1 : 0))

如果row大於或等於numRow,則row >= numRow將返回1,否則返回0。

因此,代碼行等效於以下函數:

bool foo() { 
    if(row >= numRow)
       return r < numRow - 1;
    else
       return r < numRow;
}

使用比較運算符的結果為truefalse ,當用作整數時為10

r < (numRow - (row >= numRow))

與...相同

r < (numRow - 1)如果(row >= numRow)

否則它是r < numRow

正如其他人之前所說,只是bool表達式在減法之前被row >= numRow轉換為int (這意味着:如果row >= numRow則減法1)。

但是我要補充一點,這很荒謬。 您已經斷言了row < numRow ,因此row >= numRow將違反函數的先決條件。 在下一行中, col > numCol發生同樣的情況。

暫無
暫無

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

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