访问类中的2D数组时出错

时间:2015-01-28 19:18:11

标签: c++ static const multidimensional-array

我一直在使用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

1 个答案:

答案 0 :(得分:1)

成员变量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";
};
相关问题