C++访问NeuralNewtork类Matrix2D成员报invalid use of member错误如何解决
问题原因
- 核心报错原因1:
NeuralNewtork类的成员声明错误。你在类中写的Matrix2D first_hidden_weights();属于C++的成员函数声明语法,意思是声明一个返回值为Matrix2D、无参数的成员函数first_hidden_weights,并不是声明Matrix2D类型的成员变量。编译器识别到你把函数当做对象访问成员,就会抛出对应报错。 - 核心报错原因2:构造函数内的同名局部变量屏蔽了类成员。你在构造函数里写的
Matrix2D first_hidden_weights(hidden_nodes, input_nodes);是创建了一个构造函数作用域内的局部变量,和类的成员没有任何关联,构造函数执行结束后这个局部变量就会被销毁,根本不会保留到类实例中。 - 其他潜在问题:
hidden_weights、output_weights等其余成员也存在同样的声明错误;你使用的变长数组是C++标准不支持的非标准语法;matrixMultiplication函数里循环变量写错(把k++写成i++会触发无限循环);Matrix2D没有析构函数会导致内存泄漏。
解决方法
- 首先修正
NeuralNewtork类的成员声明,把错误的函数声明改为变量声明:
class NeuralNewtork{ public: int numberof_input_nodes; int numberof_hidden_layers; int numberof_hidden_nodes; int numberof_output_nodes; // 修正为成员变量声明,动态数组用二级指针 Matrix2D first_hidden_weights; Matrix2D** hidden_weigths; Matrix2D output_weights; Matrix2D** hidden_biases; Matrix2D output_biases;
- 构造函数新增初始化列表初始化
Matrix2D成员(因为Matrix2D没有无参构造函数,必须在初始化列表传递构造参数),同时删除构造函数内的同名局部变量定义:
// 构造函数新增初始化列表 NeuralNewtork(int input_nodes, int hidden_layers, int hidden_nodes, int output_nodes) : first_hidden_weights(hidden_nodes, input_nodes), output_weights(output_nodes, hidden_nodes), output_biases(output_nodes, 1) { numberof_input_nodes = input_nodes; numberof_hidden_layers = hidden_layers; numberof_hidden_nodes = hidden_nodes; numberof_output_nodes = output_nodes; // 直接操作类成员,不要再定义同名局部变量 first_hidden_weights.randomizeMatrix(); // 用new动态分配数组替代非标准的变长数组 hidden_weigths = new Matrix2D*[numberof_hidden_layers-1]; for (int i=0; i<numberof_hidden_layers-1; i++){ hidden_weigths[i] = new Matrix2D(numberof_hidden_nodes, numberof_hidden_nodes); hidden_weigths[i]->randomizeMatrix(); } output_weights.randomizeMatrix(); hidden_biases = new Matrix2D*[numberof_hidden_layers]; for (int i=0; i<numberof_hidden_layers; i++){ hidden_biases[i] = new Matrix2D(numberof_hidden_nodes, 1); hidden_biases[i]->randomizeMatrix(); } output_biases.randomizeMatrix(); }
- 修正
matrixMultiplication里的循环变量错误:
static Matrix2D matrixMultiplication(Matrix2D x, Matrix2D y){ Matrix2D result(x.rows, y.columns); for (int i = 0; i < result.rows; i++) { for (int j = 0; j < result.columns; j++) { float sum = 0; // 把原来错误的i++改为k++ for (int k = 0; k < x.columns; k++) { sum += x.matrix[i][k] * y.matrix[k][j]; } result.matrix[i][j] = sum; } } return result; }
- 补充析构函数避免内存泄漏:
// Matrix2D类新增析构函数 ~Matrix2D(){ for (int i = 0; i < rows; i++) { delete[] matrix[i]; } delete[] matrix; } // NeuralNewtork类新增析构函数 ~NeuralNewtork(){ for (int i=0; i<numberof_hidden_layers-1; i++){ delete hidden_weigths[i]; } delete[] hidden_weigths; for (int i=0; i<numberof_hidden_layers; i++){ delete hidden_biases[i]; } delete[] hidden_biases; }
修改完成后,你原来的nn.first_hidden_weights.printMatrix();代码就可以正常执行打印权重矩阵。
内容的提问来源于stack exchange,提问作者SnowballAvocado
相关产品推荐
相关产品推荐

