在另一个成员函数中使用时,C ++成员函数错误“未声明的标识符”

时间:2012-10-03 00:48:47

标签: c++ function undeclared-identifier

我认为这是在我的声明中,但我不确定。有一个班级" Matrix"它创建int类型的二维数组。该类有几个重载运算符,用于对类对象执行算术等。

一个要求是检查矩阵是否具有相同的尺寸。尺寸存储 作为两个私人投资" 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
    }
}

2 个答案:

答案 0 :(得分:1)

您的operator*未在Matrix范围内定义。您实际上已经定义了一个全局运算符。你需要

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

然后应该没问题。注意,如果这已经编译过,那么您将获得一个链接器&undefined引用运算符Matrix :: operator *&#39;错误,因为没有定义。

答案 1 :(得分:0)

仅需要bool函数来支持算术函数。其中一些函数可以是成员重载运算符,有些可以是朋友。这里的诀窍是将bool函数定义为朋友,使成员直接函数和朋友函数都可以访问它,同时保留访问私有成员数据的能力。

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