简体   繁体   English

在类内访问2D数组时出错

[英]Error in accessing a 2D array inside a class

I have been working on a code in C++. 我一直在用C ++编写代码。 But, I got stuck at a point. 但是,我陷入了困境。

This is a small prototype of my code:: 这是我的代码的一个小原型:

#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;
}

I create a class funPublic() method, where I create a 2D array (using the const int var, which I declare as a private member inside my class Test ) and then pass it to a private methode funPrivate(int arr[][var], int temp) , where I print arr[0][0] (which shall be a garbage value). 我创建了一个funPublic()类方法,在其中创建了2D数组(使用const int var,我在类Test声明为私有成员),然后将其传递给私有方法funPrivate(int arr[][var], int temp) ,在此打印arr[0][0] (应为垃圾值)。

But, when I try to run this program, I get an error:: 但是,当我尝试运行该程序时,出现错误:

error: invalid use of non-static data member 'Test::var'

My method funPrivate(int arr[][var], int temp) is a normal function (not a static function) and I don't a reason that I shall declare int var as static. 我的方法funPrivate(int arr[][var], int temp)是一个普通函数(不是静态函数),我没有理由将int var声明为静态。 Why does this happen. 为什么会这样。

Further, if I slightly modify the declaration of my method 'funPrivate(int arr[][var], int temp)' to this void funPrivate(int arr[][var]) then I get one more error: 此外,如果我将方法'funPrivate(int arr [] [var],int temp)'的声明稍加修改为此void funPrivate(int arr[][var])则会收到一个错误:

error: 'arr' was not declared in this scope

Now, I don't know why does that happen. 现在,我不知道为什么会这样。 We pass the size of the array for our convenience, because there is no way to determine the size of the array in a function, but that shall not cause the error that arr was not declared in this scope . 为了方便起见,我们传递了数组的大小,因为无法确定函数中数组的大小,但这不会导致arr was not declared in this scope的错误。

I have been thinking and searching a lot, but still can't find an answer. 我一直在想和搜索很多,但仍然找不到答案。 Please help. 请帮忙。 Thanks for any help in advance. 感谢您的任何帮助。 :D :d

The member variable var cannot be used in the declaration of an array like you are attempting in the function funPrivate : 成员变量var不能像在funPrivate函数中funPrivate在数组的声明中使用:

void funPrivate(int arr[][var], int temp)

Your best option is to use std::vector<std::vector<int>> . 最好的选择是使用std::vector<std::vector<int>>

void funPrivate(std::vector<std::vector<int>> const& arr, int temp) {
    cout << arr[0][0] << endl;
}

In the calling function, you can use: 在调用函数中,可以使用:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM