gpt4 book ai didi

C++ 无法将普通二维数组传递给方法

转载 作者:搜寻专家 更新时间:2023-10-31 02:20:41 25 4
gpt4 key购买 nike

我正在创建一个以二维数组作为变量的类。我希望该类的用户能够将它与在堆栈上创建的普通二维数组 ( int array[3][3] ) 一起使用,或者能够将它与堆上的动态二维数组 ( int *array [3])。然后我会用传入的数组填充我类(class)的二维数组,不管它是什么类型。

我看过这篇文章:Passing a 2D array to a C++ function和其他一些非常相似。我遵循了答案,但我仍然遇到问题。这是我正在做的:

我的类称为 CurrentState,我有两个具有不同签名的构造函数。

当前状态.h

#ifndef A_STAR_CURRENTSTATE_H
#define A_STAR_CURRENTSTATE_H

class CurrentState
{
private:
int state[3][3];

public:
CurrentState(int** state); // Dynamic array
CurrentState(int state[][3]); // Normal array
bool isFinishedState;
bool checkFinishedState();
};

#endif

当前状态.cpp

#include <iostream>
#include "currentState.h"

CurrentState::CurrentState(int** state) {

// Fill class's state array with incoming array
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
this->state[i][j] = state[i][j];
}
}

CurrentState::CurrentState(int state[][3])
{
// Fill class's state array with incoming array
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
this->state[i][j] = state[i][j];
}
}

然后在我的 main() 方法中我这样做:

#include <iostream>
#include "currentState.h"

using namespace std;



int main()
{
// Make dynamic array and pass into constructor
int *array[3];
for (int i = 0; i < 3; i++)
array[i] = new int[3];

CurrentState dynamic(array);

// Make normal array and pass into constructor
int a[3][3];

CurrentState onStack(a); // <-- error says: "Class 'CurrentState' does not have a constructor 'CurrentState(int [3][3])'"


return 0;
}

第一次使用动态数组在 main() 中启动 CurrentState 工作正常,但是第二次使用普通数组启动 CurrentState 会出错。

我正在使用 JetBrains 的 CLion IDE,该方法带有红色下划线并表示:“Class 'CurrentState' does not have a constructor 'CurrentState(int[3][3])'”

我错过了什么吗?我很确定类 确实 有一个普通数组 ( int[3][3] ) 的构造函数。

在我的搜索中,我看到许多其他人在做同样的事情,就像这里:http://www.cplusplus.com/forum/beginner/73432/以及我在帖子开头发布的链接。

我是不是忽略了什么?任何帮助将不胜感激。

编辑

我已经从数组中删除了第一个参数,并把它变成了这样:

CurrentState(int state[][3]);

我仍然有同样的错误

编辑

它可以从命令行编译,但不能从 IDE 中编译。我会在编码时忽略错误。虚惊。对不起大家。

最佳答案

从函数定义中的括号中删除第一个值。

像这样:

CurrentState::CurrentState(int state[][3])
{
...
}

我还强烈建议使用 std::arraystd::vector 而不是 c 风格的数组。除非您在下面添加释放循环,否则您的动态分配代码已经泄漏内存。

int *array[3];
for (int i = 0; i < 3; i++)
array[i] = new int[3];

CurrentState dynamic(array);

//Kind of ugly cleanup here
for (int i = 0; i < 3; i++)
delete[] array[i];

关于C++ 无法将普通二维数组传递给方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32406320/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com