无法将结构传递给另一个文件中声明的功能?

Can't pass struct to function declared in another file?

本文关键字:文件 声明 功能 另一个 结构      更新时间:2024-09-22

我有一系列变量,包括在另一个文件(Vek.h(中声明的结构。在这个文件中,我还声明了一个名为correct:的函数

class Vek: public Player{
protected :
int counter = 0; 
struct next {int nexti=0; int nextj=0;};
next newNext = {0,0};
int jTemp; 
int iTemp = 0;
int jPast;
int iPast;
int hits;
int pastHits = 0;
int count = 0;
void putShip(Cell[OCEAN_SIZE][OCEAN_SIZE]);
int correct(int, int, int, int, int, int, struct);
// int fire(vector<int>submit);
Coords shot;

在第二个文件(Vek.cpp(中,我尝试调用此函数并将结构体next作为参数传递:

int Vek :: correct(int iTemp, int jTemp, int iPast, int jPast, int hits, int count, struct newNext){
int attemptsi[2]{iTemp+1,iTemp-1};
int attemptsj[2]{jTemp+1,jTemp-1};
int i;
int j; 
if(count == 0){
i = attemptsi[0];
j = jTemp;
// Coordinates.j = 5;
}else if(count == 1){
i = attemptsi[1];
j = jTemp;
// Coordinates.j = 5;
}else if(count == 2){
i = iTemp; 
j = attemptsj[0];
// Coordinates.j = 5;
}else if(count == 3){
i = iTemp;
j = attemptsj[1];
// Coordinates.j = 5;
}
next.nexti = i; 
next.nextj = j; 

count++;
return next; 
}

由于结构的原因,我在调用correct时出错。在其他人中,我得到了错误:

"correct"的越界定义与任何"Vek"中的声明

这里发生了什么?如何将结构体next传递给correct函数?

如果correct周围没有空格,我会得到错误:

匿名结构的声明必须是定义

结构的定义由组成

  • 关键字struct
  • 通常是结构的(类型(名称
  • 结构体,大括号中

示例:

struct    Int_Struct    { int mI; };
^           ^              ^ 
keyword      name           body

名称(此处为Int_Struct(可以直接用作类型名称(与C不同(。

该类型变量的定义遵循通常的约定typename variablename:

Int_Struct myVar;一如既往,对于函数参数的声明也是如此:

void f(Int_Struct myParam);

您可以在原型中,或者如果没有使用参数,则省略参数名称,只需编写void f(Int_Struct);。但是典型地;说";给出了参数名称,以便读者了解参数的内容;最好的文档是自文档。

关键字struct不能用作类型名称,就像在函数定义int Vek :: correct(int iTemp, int jTemp, int iPast, int jPast, int hits, int count,structnewNext)中对最后一个参数所做的那样:记住,参数声明的形式为typename parametername,这使得struct成为类型名称,正如所述,这是不可能的。如果您希望在参数或变量声明中以C方式冗余地使用关键字struct作为类型名称的部分struct Int_Struct varName;相当于更惯用和常见的Int_Struct varName;