[英]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)
是一個布爾表達式,當像這樣使用時,將其轉換為一個int
, true
變為1
, false
變為0
一種更清晰的表達方式可能是:
r < (row >= numRow ? numRow - 1 : numRow)
row >= numRow
將返回布爾值true或false,即隱式轉換為整數0
或1
。 所以這樣做基本上與以下內容相同:
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;
}
使用比較運算符的結果為true
或false
,當用作整數時為1
或0
。
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.