【问题标题】:Why will this not compile with mingw in Code::Blocks?为什么这不能在 Code::Blocks 中使用 mingw 编译?
【发布时间】:2014-10-07 03:51:53
【问题描述】:

我已将其简化为基本代码。本质上,我需要将二维数组传递给函数,但数组的大小是在执行时从文本文件中读取的。我读过的关于这个主题的所有内容都说这是这样做的方法,但编译器却说不然。代码如下:

#include <iostream>

using namespace std;

template <size_t r, size_t c>
void func(int (&a)[r][c])
{
    return;
}

int main()
{
    int rows = 5;
    int cols = 6;
    int Array[rows][cols];

    func(Array);

    return 0;
}

我宁愿避免使用向量,因为我对它们非常陌生。这是编译器的输出:

-------------- Build: Debug in test (compiler: GNU GCC Compiler)---------------

mingw32-g++.exe -Wall -fexceptions -g  -c C:\Users\ME\Desktop\test\test\main.cpp -o obj\Debug\main.o
C:\Users\ME\Desktop\test\test\main.cpp: In function 'int main()':
C:\Users\ME\Desktop\test\test\main.cpp:20:15: error: no matching function for call to 'func(int [(((unsigned int)(((int)rows) + -0x000000001)) + 1)][(((unsigned int)(((int)cols) + -0x000000001)) + 1)])'
C:\Users\ME\Desktop\test\test\main.cpp:20:15: note: candidate is:
C:\Users\ME\Desktop\test\test\main.cpp:6:25: note: template<unsigned int r, unsigned int c> void func(int (&)[r][c])
Process terminated with status 1 (0 minute(s), 0 second(s))
1 error(s), 0 warning(s) (0 minute(s), 0 second(s))

【问题讨论】:

    标签: c++ arrays compiler-errors g++ mingw


    【解决方案1】:

    在这段代码中

    int rows = 5;
    int cols = 6;
    int Array[rows][cols];
    

    Array 不是普通的 C++ 多维数组,而是 C99 可变长度数组,即 VLA。

    这不是标准的 C++。

    改为

    int const rows = 5;
    int const cols = 6;
    int Array[rows][cols];
    

    这是因为初始化表达式在编译时是已知的。


    为避免此类问题,请将选项 -pedantic-errors 添加到您的 g++ 调用中。

    【讨论】:

    • 我只是使用“rows”和“cols”作为替代。行数和列数将在运行时从文本文件中读取。鉴于此,这仍然有效吗?
    • @bobsicle0 不。从文本文件中读取的数字在编译时是未知的。使用std::vector 进行存储。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多