[英]C++ can't pass normal 2D array into method
我正在創建一個將二維數組作為變量的類。 我希望該類的用戶能夠將它與在堆棧上創建的普通二維數組( int array[3][3] )一起使用,或者能夠與堆上的動態二維數組( int *array [3])。 然后我將用傳入的數組填充我班級的二維數組,無論它是哪種類型。
我看過這篇文章: 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,該方法用紅色下划線表示:“類 'CurrentState' 沒有構造函數 '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::array
或std::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];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.