c++ - 访问类内的二维数组时出错

标签 c++ static constants multidimensional-array

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

相关文章:

c++ - 使用 const 指针初始化 const 结构

php - 如何获取常量的名称?

c++ - 位域和编译指示

c++ - 有没有办法在不加载的情况下读取 .so 文件的内容?

java - 为什么方法不是静态的却说它是静态的?

java - 如何在不实际运行 Java 类的情况下分析它的性能?

c++ - 将 unique_ptr<Object> 作为 unique_ptr<const Object> 返回

c++ - 为什么 C++ 流使用 char 而不是 unsigned char?

c++ - 结构体用malloc分配,为什么? C++代码分析

c++ - Windows的静态库检查器?