繁体   English   中英

在 C++ 类中声明多维数组的正确方法是什么

[英]What is the correct way to declare multi-dimensional array inside C++ class

当我尝试在 C++ 中声明一个数组时,总是令人沮丧。 也许我只是不明白数组是如何工作的。 以下情况是我正在编写一个构造函数来初始化行、列和多维数组。 代码运行出错。

我已经在私有类成员中声明了 row、col 和 array 变量。 当我运行 main 时,row 和 col 将传递给构造函数。 数组应该初始化成功?

#include <bits/stdc++.h>
using namespace std;

class SpreadSheet {
private:
  int r, c;
  string table[r][c];

public:
  SpreadSheet(int row, int col) {
    r = row; c = col;

    for (int i = 0; i < r; i++) {
      for (int j = 0; j < c; j++) {
        table[i][j] = ' ';
      }
    }
  }
};

int main() {
  SpreadSheet t(3, 3);

  return 0;
}

下面是我得到的错误日志。 我想我明白它背后的基本逻辑。 必须在编译代码之前分配数组大小。 那么解决这个问题的正确方法是什么?

demo.cc:7:16: error: invalid use of non-static data member ‘SpreadSheet::r’
    7 |   string table[r][c];
      |                ^
demo.cc:6:7: note: declared here
    6 |   int r, c;
      |       ^
demo.cc:7:19: error: invalid use of non-static data member ‘SpreadSheet::c’
    7 |   string table[r][c];
      |                   ^
demo.cc:6:10: note: declared here
    6 |   int r, c;
      |          ^
demo.cc: In constructor ‘SpreadSheet::SpreadSheet(int, int)’:
demo.cc:15:9: error: ‘table’ was not declared in this scope
   15 |         table[i][j] = ' ';
      |
string table[r][c];

无效,因为编译器已经让你知道了。

rc必须在编译时知道,以便您能够使用它们来声明数组。

您可以使用

std::vector<std::vector<std::string>> table;

并确保在类的构造函数中适当地初始化它。

SpreadSheet(int row, int col) : table(row, std::vector<std::string>(col, " "))
{
 ...
}

如果使用它,则不需要成员变量rc 如果行数大于零,可以使用table.size()获取行数,使用table[0].size() table.size()获取列数。

该类的发布代码可以简化为

class SpreadSheet {
  private:
    std::vector<std::vector<std::string>> table;

  public:
    SpreadSheet(int row, int col) : table(row, std::vector<std::string>(col, " ")) {}
};

VLA(可变长度数组)在 C++ 中不受支持(并且无论如何都不应该在 C 中使用)。

变量的大小必须在编译时已知,这意味着您不能定义大小未知(在编译时)的对象,例如示例中的类。

如果您想要一个“动态数组”,请使用标准的std::vector 特别是,如果您有一个矩形表,最好的方法是声明一个:

std::vector<std::string> table;

并为r * c元素初始化/调整它的大小。

我不会使用像x[r][c]这样的 C 风格数组。 更好的解决方案是vectorvector ,如 R Sahu 的回答中所述。

但是,如果您真的想使用 C 风格的数组,则可以使用如下模板:

template <int r, int c> class SpreadSheet 
{
    string table[r][c];
};

int main() {
    SpreadSheet<3, 3> t;
    ...

另一种解决方案是指针而不是数组。

   class SpreadSheet {
private:
  int r, c;
  string **table;

public:
  SpreadSheet(int row, int col) {
    r = row; c = col;

    table = new string*[r];
    for (int i = 0; i < r; ++i)
    {
        table[i] = new string[c];
    }

    for (int i = 0; i < r; i++) {
      for (int j = 0; j < c; j++) {
        table[i][j] = ' ';
      }
    }
  }
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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