C++报错‘a nonstatic member reference must be relative to a specific object’求解
问题分析与修复方案
错误根源
你代码里的print函数参数int mat[a][b]违反了C++的规则:类的非静态成员a、b属于具体的对象实例,而函数参数列表里的数组维度要求在编译期就能确定。编译器在解析函数签名时,还没有绑定到任何具体对象,自然无法获取a和b的值,因此抛出编译错误。
可行的修复方式
方式1:使用模板适配编译期维度
如果数组的行列数在编译时就能确定,用模板类可以完美解决问题:
#include<bits/stdc++.h> using namespace std; template<int Rows, int Cols> class test { public: void print(int mat[Rows][Cols]) { for (int i = 0; i < Rows; ++i) { for (int j = 0; j < Cols; ++j) { cout << mat[i][j] << " "; } } } }; int main() { int mat[3][2] = {{2,3},{4,5},{6,7}}; test<3,2> arr; arr.print(mat); return 0; }
方式2:改用std::vector实现动态二维数组
如果行列数需要在运行时确定,用std::vector这种动态容器是更符合C++风格的选择:
#include<bits/stdc++.h> using namespace std; class test { int rows, cols; public: void intake(int x, int y) { rows = x; cols = y; } void print(const vector<vector<int>>& mat) { for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { cout << mat[i][j] << " "; } } } }; int main() { vector<vector<int>> mat = {{2,3},{4,5},{6,7}}; test arr; arr.intake(3,2); arr.print(mat); return 0; }
方式3:指针+维度参数传递
如果你坚持使用静态数组,可以把二维数组转成一维指针传递,同时依赖之前设置的行列值来遍历:
#include<bits/stdc++.h> using namespace std; class test { int rows, cols; public: void intake(int x, int y) { rows = x; cols = y; } void print(int* mat) { for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { cout << *(mat + i*cols + j) << " "; } } } }; int main() { int mat[3][2] = {{2,3},{4,5},{6,7}}; test arr; arr.intake(3,2); arr.print(&mat[0][0]); return 0; }
内容的提问来源于stack exchange,提问作者Rohan Bhardwaj
相关产品推荐
相关产品推荐

