尝试在 main 中调用函数时出错

Error when trying to call a function in main.

本文关键字:函数 出错 调用 main      更新时间:2023-10-16

我正在尝试在我尝试从 C 转换为 C++ 的程序中调用我的 main 中的一个函数。我在其他函数中的所有函数调用都可以编译而没有错误,但是当它到达主函数中的一个函数调用时,我得到了no matching function for call to contacts::menu(contacts*[5], int*, int&, char[50])'

这是主要的:

int main() {

 contacts *friends[5];
 char buffer[BUFFSIZE];
 int counter=0;
 int i=0;
 contacts::menu(friends, &counter,i,buffer);
 getch();
 return 0;
}

下面是带有函数声明的类:

class contacts
{
  private:
          char *First_Name;
          char *Last_Name;
          char *home;
          char *cell;
  public:
  //constructor
         contacts()
         {
         }       
//Function declarations 
static void menu(contacts*friends ,int* counter,int i,char buffer[]);
};

这是菜单功能的开头部分,只是为了让你了解它被标记了什么:

void contacts::menu(contacts*friends,int* counter, int i,char buffer[]) 
{
  int user_entry=0;
  int user_entry1=0;
  int user_entry2=0;
  char user_entry3[50]={''};
  FILE *read;
  printf("Welcome! Would you like to import a file? (1)Yes or (2) No");
  scanf("%d",&user_entry1);
  if(user_entry1==1)
    {
     printf("Please enter a file name");
     scanf("%s",user_entry3); 
     read=fopen(user_entry3,"r+");

就像我说的,我的程序中的其他函数没有收到任何错误,但这个函数会收到。我是C++新手,所以我不确定是否需要添加一些特殊的东西来调用 main 中的函数。

这是问题所在

 contacts *friends[5];

你传递给

void contacts::menu(contacts*friends,int* counter, int i,char buffer[]) 

您已经声明了一个指向contacts的指针数组,当您将其传递给函数时,它会衰减为contacts**

要将函数与其当前签名一起使用,您需要将friends数组声明为

contacts* friends = new contacts[5];

contacts friends[5];

在后一种情况下,将数组传递给函数将起作用,因为它将衰减到函数所期望的contacts*。后一种情况更可取,因为您不必担心在第一种情况下使用 new

int main() { contacts friends[5];

您的代码将编译。

菜单函数在您尝试传递contacts*[]时需要contacts*作为第一个参数