2012-10-03 38 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 *'中。 –

相关问题