C++ 成员函数错误 在另一个成员函数中使用时"Undeclared Identifier"
C++ Member Function errors "Undeclared Identifier" when used within another Member Function
我认为这是我的声明,但我不确定。有一个类"矩阵",它创建 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);
相关文章:
- 如何使用指针传递给函数的数组中对象的函数成员
- c++构造函数成员初始化:传递参数
- 创建 std::函数,它返回具有函数成员值的变量.分段错误
- 如何在C++通过公共函数访问私有函数成员?
- 解释了构造函数成员初始化列表
- 调用std::函数成员时内存损坏
- 是否可以为模板类的模板函数成员设置别名?
- 捕获 lambda 函数C++成员变量
- 构造函数成员初始值设定项跨成员列出,安全吗?
- 获取与在模板参数中传递的函数成员类型相同的类
- 如何从公共函数成员访问地图私有成员
- C 构造函数成员分配优化
- 使用命名空间进行函数成员定义
- 函数成员作为 CUDA 内核的参数
- 模板基类函数成员的别名
- 函数成员中用于void和继承的enable_if
- 头文件中是否定义了一个很长的Class函数成员
- 类内/构造函数成员初始化
- 使用指向部分专用函数成员的指针自动填充向量
- 指向函数成员的指针