我一直在用 C++ 编写代码。但是,我卡住了。
这是我的代码的一个小原型(prototype)::
#include <iostream>
using namespace std;
class Test{
private:
const int var;
void funPrivate(int arr[][var], int temp){
cout << arr[0][0] << endl;
}
public:
Test(int n) : var(n){};
void funPublic(){
int a[var][var];
funPrivate(a, var);
cout << "Hello";
};
};
int main()
{
Test t1(5);
t1.funPublic();
return 0;
}
我创建了一个类 funPublic()
方法,我在其中创建了一个二维数组(使用 const int var,我在类 Test
中将其声明为私有(private)成员) 然后将其传递给私有(private)方法 funPrivate(int arr[][var], int temp)
,我在其中打印 arr[0][0]
(应成为垃圾值)。
但是,当我尝试运行这个程序时,我得到一个错误::
错误:无效使用非静态数据成员“Test::var”
我的方法 funPrivate(int arr[][var], int temp)
是一个普通函数(不是静态函数),我没有理由声明 int var
为静态。为什么会这样。
此外,如果我将我的方法“funPrivate(int arr[][var], int temp)”的声明稍微修改为这个 void funPrivate(int arr[][var])
然后我又收到一个错误:
错误:“arr”未在此范围内声明
现在,我不知道为什么会这样。我们传递数组的大小是为了方便,因为在函数中无法确定数组的大小,但这不会导致 arr was not declared in this scope
的错误。
我一直在思考和寻找很多,但仍然找不到答案。请帮忙。感谢您提前提供帮助。 :D
最佳答案
成员变量var
不能像您在函数 funPrivate
中尝试的那样在数组声明中使用:
void funPrivate(int arr[][var], int temp)
您最好的选择是使用 std::vector<std::vector<int>>
.
void funPrivate(std::vector<std::vector<int>> const& arr, int temp) {
cout << arr[0][0] << endl;
}
在调用函数中,可以使用:
void funPublic(){
std::vector<std::vector<int>> arr(var, std::vector<int>(var));
funPrivate(arr, var);
cout << "Hello";
};
关于c++ - 访问类内的二维数组时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28200582/