2012-10-03 36 views
0

我在想這是在我的聲明中,但我不確定。有一個創建類型爲int的2維數組的類「Matrix」。該類有幾個重載操作符來對類對象執行算術等。當在另一個成員函數內使用C++成員函數錯誤「未聲明標識符」

一個要求是檢查矩陣具有相同的尺寸。尺寸被存儲爲 作爲兩個私人整數「dx」和「dy」。

所以爲了使這個效率更高,我寫了一個類型爲bool的成員函數,如下所示;

bool confirmArrays(const Matrix& matrix1, const Matrix& matrix2);

是函數頭和聲明;

bool Matrix::confirmArrays(const Matrix& matrix1, const Matrix& matrix2) 
{ 
    if (matrix1.dx == matrix2.dx && matrix1.dy == matrix2.dy) 
    { 
     // continue with operation 
     return true; 

    } else { 

     // hault operation, alert user 
     cout << "these matrices are of different dimensions!" << endl; 
     return false; 
    } 
} 

但是當我打電話confirmArrays從另一個成員函數中我得到這個錯誤;

使用未聲明的標識符的confirmArrays

調用像這樣的功能;

// matrix multiplication, overloaded * operator 
Matrix operator * (const Matrix& matrix1, const Matrix& matrix2) 
{ 
    Matrix product(matrix1.dx, matrix2.dy); 
    if (confirmArrays(matrix1, matrix2)) 
    { 
     for (int i=0; i<product.dx; ++i) { 
      for (int j=0; j<product.dy; ++j) { 
       for (int k=0; k<matrix1.dy; ++k) { 
        product.p[i][j] += matrix1.p[i][k] * matrix2.p[k][j]; 
       } 
      } 
     } 
     return product; 

    } else { 

     // perform this when matrices are not of same dimensions 
    } 
} 
+1

需要看到您的調用代碼,我認爲。 –

+0

其實我認爲如果調用函數在'confirmArrays'之前聲明的話 - 很難看到它可能是什麼。編輯 - 只是做了一點測試,順序應該不重要,但也許嘗試。 –

+0

瘋狂的猜測:你是從'const'成員函數調用它的嗎?你需要使它成爲'const'(或者更好的是'static',或者可能是'friend',因爲它實際上並不訪問它所調用的對象)才能做到這一點。沒有看到它的名稱和方式,猜測就是最好的。 –

回答

1

您的operator*未在Matrix的範圍內定義。你已經定義了一個全球運營商。你需要

Matrix Matrix::operator * (const Matrix& matrix1, const Matrix& matrix2) 
{ 
    ... 
} 

然後它應該沒問題。注意,如果這已經編譯完成,你將會得到一個鏈接器'對運算符Matrix :: operator *'的未定義引用,因爲它沒有被定義。

+0

它被定義爲朋友; '朋友矩陣運算符*(常數矩陣&矩陣1,矩陣矩陣&矩陣2);' – frankV

+0

@frankV好吧,但在這種情況下,您正在調用'confirmArrays'而沒有實例。那裏的解決方案將聲明'confirmArrays'爲'static'。 –

+0

對不起@Matt菲利普斯,試圖...同樣的錯誤 – frankV

0

bool函數僅用於支持算術函數。其中一些功能可以是成員重載操作員,有些可以是朋友。這裏的技巧是將bool函數定義爲朋友,使其可以訪問成員直接函數和朋友函數,同時保留訪問私有成員數據的能力。

friend bool confirmArrays(const Matrix& matrix1, const Matrix& matrix2);

+0

這裏有點問題。如果'confirmArrays'是一個非靜態成員函數('Matrix'的成員),那麼不能在沒有對象的情況下調用它,因爲它在'operator *'中。 –

相關問題