c++ - 有人可以解释一下,为什么我的代码不起作用?

标签 c++

我是 C++ 的新手,我必须解决一个大学任务,我必须创建一个结构矩阵并用随机整数填充它。我用“!”标记了这一行出现错误的地方。 这是错误 C2131(Visual C++ 编译器)。它说“表达式未计算为常量”。

struct Matrix{
   int rows;
   int columns;
   Matrix(int r, int c){
      rows = r, columns = c;
   }
   int produceMatrix(){
       int matrix[rows][columns];  "!"
       for(int i = 0; i != rows; i++){
           for(int j = 0; j != columns; j++){
               matrix[i][j] = rand() %10 +1;
           }
       }
       return 0;
   }
   int showMatrix(){
       for(int i = 0; i != rows; i++){
           for(int j = 0; j != columns; j++){
               cout << matrix[i][j]<< endl;
           }
       }
   }
};


int main()
{
    srand(time(0));
    Matrix a(3, 4);

}    

最佳答案

如果您计划使用 rows 创建矩阵和 columns仅在运行时已知的值,您最好使用 std::vector<std::vector<int>>来保存你的数据,因为你使用的静态数组需要在编译时知道它的大小。但是如果你所有的大小在编译时都是已知的并且你只是想灵活地创建不同的矩阵大小,你可以使用模板,例如:

#include <iostream>
#include <ctime>

template <int ROWS, int COLUMNS>
struct Matrix
{
    int rows = ROWS;
    int columns = COLUMNS;
    int matrix[ROWS][COLUMNS] = {};

    void produceMatrix()
    {
        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < columns; j++)
            {
                matrix[i][j] = rand() % 10 + 1;
            }
        }
    }

    void showMatrix()
    {
        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < columns; j++)
            {
                std::cout << matrix[i][j] << "\t";
            }
            std::cout << std::endl;
        }
    }
};


int main()
{
    srand(time(0));
    Matrix<3,4> a;
    a.produceMatrix();
    a.showMatrix();
}

https://ideone.com/rCLxSn

4   10  5   5   
3   8   3   6   
2   4   9   10

关于c++ - 有人可以解释一下,为什么我的代码不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50542836/

相关文章:

c++ - 是否可以为 C++ 文件生成依赖项列表?

c++ - C++指针的地址

c++ - 使用 Nuwen 设置英特尔 TBB

c++ - 为什么该代码不绘制 Sprite C++ SFML

c++ - 我如何让 Doxygen 扩展包含文件中的宏?

c++ - 复制构造函数问题

c++ - 表达式 : _CrtlsValidHeapPointer(pUserData) error

c++ - GCC优化isnan(x)是否可行|| isnan(y) 变成 isunordered(x, y)?

c++ - 从 C++ 程序调用 python 进行分发

c++ - std::string& 与 boost::string_ref