C++ 成员函数错误 在另一个成员函数中使用时"Undeclared Identifier"

C++ Member Function errors "Undeclared Identifier" when used within another Member Function

本文关键字:函数 成员 Identifier Undeclared 错误 另一个 C++      更新时间:2023-10-16

我认为这是我的声明,但我不确定。有一个类"矩阵",它创建 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
    }
}

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

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

然后应该没问题。 注意,如果这已经编译,你会得到一个链接器"未定义对运算符矩阵的引用::operator*"错误,因为它没有定义。

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

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