2013-03-26 77 views
0

我遇到以下問題。我實現矩陣。整個矩陣有一個類,矩陣的一行有一個類。我創建了行,以便我可以訪問像矩陣[a] [b]那樣的成員。但問題是拋出異常,必須以這種格式「無效索引[e] [f]」。我會在矩陣重載[]中使用try-catch,並且從Rows overload []引發整數異常,但是它並不能解決第一個索引正確且第二個索引錯誤的情況。2D中的索引異常

//Matrix overload 
Row& operator [] (unsigned inx) { 
return *rows[inx]; 
} 

//Row overload 
double& operator [] (unsigned inx) 
{ 
return items[inx]; 
} 
+0

你不能重載只是返回類型。重載需要一個不同的簽名。 – Freddy 2013-03-26 21:13:16

+1

讓'Row'對象跟蹤它所關聯的索引。 – 2013-03-26 21:13:28

+2

@Freddy它們在不同的類中實現。是的,這個問題並不完全清楚。 – 2013-03-26 21:13:33

回答

1

例外必須是像格式 「無效的指數[E] [F]」

這是棘手比它的聲音!

如果[f]無效,Matrix::operator[](e)已經完成。該參數不再可用。

因此,您需要將此信息傳遞給有問題的。這是一種方法。

// (Member variable "int Row::index" is added...) 

//Matrix overload 
Row& operator [] (unsigned inx) { 
    rows[inx]->setRowIndex(inx); 
    return *rows[inx]; 
} 

//Row overload 
double& operator [] (unsigned inx) 
{ 
    // Now you can throw information about both inx and the stored row index 
    return items[inx]; 
} 

如果[e]是無效的,Row::operator[](f)尚未調用。這是一個未知的價值。

這意味着,即使[e]無效,它必須返回一些operator[]仍然可以在拋出之前調用。

// (Member variable "bool Row::isInvalid" is added...) 

//Matrix overload 
Row& operator [] (unsigned inx) { 
    Row *result; 
    if (inx is invalid) 
    { 
    // Don't throw yet! 
    static Row dummy; 
    dummy.setInvalid(); 
    result = &dummy; 
    } 
    else 
    { 
    result = rows[inx]; 
    } 
    result->setRowIndex(inx); 
    return *result; 
} 

//Row overload 
double& operator [] (unsigned inx) 
{ 
    // If this->isInvalid is true, the first index was bad. 
    // If inx is invalid, the second index was bad. 
    // Either way, we have both indices now and may throw! 
    return items[inx]; 
} 
+0

非常感謝,它完美的作品。 – user1890078 2013-03-26 22:37:38