[英]Error in accessing a 2D array inside a class
我一直在用C ++编写代码。 但是,我陷入了困境。
这是我的代码的一个小原型:
#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()
类方法,在其中创建了2D数组(使用const int var,我在类Test
声明为私有成员),然后将其传递给私有方法funPrivate(int arr[][var], int temp)
,在此打印arr[0][0]
(应为垃圾值)。
但是,当我尝试运行该程序时,出现错误:
error: invalid use of non-static data member 'Test::var'
我的方法funPrivate(int arr[][var], int temp)
是一个普通函数(不是静态函数),我没有理由将int var
声明为静态。 为什么会这样。
此外,如果我将方法'funPrivate(int arr [] [var],int temp)'的声明稍加修改为此void funPrivate(int arr[][var])
则会收到一个错误:
error: 'arr' was not declared in this scope
现在,我不知道为什么会这样。 为了方便起见,我们传递了数组的大小,因为无法确定函数中数组的大小,但这不会导致arr was not declared in this scope
的错误。
我一直在想和搜索很多,但仍然找不到答案。 请帮忙。 感谢您的任何帮助。 :d
成员变量var
不能像在funPrivate
函数中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";
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.