C++函数调用二维数组

标签 c++ arrays

<分区>

我在 County.h 类中有构造函数:

struct Country {
    Country(double**, int);
};

在 main 中,我有 graph[Size][Size],我想为 County 调用构造函数。

int main() {
    double graph[Size][Size];
    Country c(graph, 0);
}

但它给了我错误没有匹配函数调用‘County::County(double [22][22], int)’

我能做些什么来解决这个问题?

最佳答案

double [Size][Size]double** 根本不是同一类型。这是您的编译器不喜欢的。

更改构造函数原型(prototype)或声明数组的方式。但是你不能直接将数组的数组转换为指针的指针。

struct Country {
    Country(double[Size][Size], int);
};

或者:

int main() {
    double** graph = new (double*)[Size];
    for (int i = 0; i < Size; ++i) {
        graph[i] = new double[Size];
    }
    Country c(graph, 0);

    // Don't forget to delete your graph then.
}

请注意,第一个要求您在代码开始执行之前知道大小(例如,将 Size 存储在宏中),但第二个需要更长的代码,您将必须操作更多的 RAM 内存,如果不小心,可能会导致错误。

关于C++函数调用二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30055339/

相关文章:

c++ - 无法将 Lua for Windows 安装嵌入到 C++ 程序中

c++ - 为什么相同的类型不同?

c - 程序先绕过fgets

javascript - 为什么长度为 1 的数组在 JavaScript 中表现得像标量?

javascript - 将前面的总和添加到数组 - javascript

c - 知道c中数组的大小

c++ - "Request for member which is of non-class type", 赋值语句不正确?

c++ - 运算符重载错误 "no match for operator error"

c++ - 如何将信号附加到动态创建的对象的插槽

java - 混合两个数组