繁体   English   中英

在 C++ 中调用函数

[英]calling functions in C++

我试图在 C++ 中调用一个函数,我认为它与 C 中的函数相同,但是在尝试将 C 程序转换为 C++ 时,我遇到了一个错误,它说函数未声明。

这是我的课:

class contacts
 {
  private:;
          char *First_Name;
          char *Last_Name;
          char *home;
          char *cell;
  public:;
  //constructor
         contacts()
         {
         }  
//Function declaration     
void readfile (contacts*friends ,int* counter, int i,char buffer[],FILE*read,char user_entry3[]);

  };

这是我的菜单功能的一个片段:

 if(user_entry1==1)
  {
    printf("Please enter a file name");
    scanf("%s",user_entry3); 
    read=fopen(user_entry3,"r+");

   //This is the "undeclared" function
   readfile(friends ,counter,i,buffer,read,user_entry3);
   }else;

我显然做错了什么,但是每次我尝试编译时,我都会得到readfile undeclared(first use this function)我在这里做错了什么?

您需要创建一个contacts类的对象,然后在该对象上调用readfile 像这样: contacts c; c.readfile(); contacts c; c.readfile(); .

班级内部的“菜单”功能是否有contacts 按照您的设计方式,它只能在类的实例上调用。 您可以根据readfilecontacts确切含义进行选择

我猜该函数读取所有联系人而不仅仅是 1 个联系人,这意味着它可以成为静态函数

static void readfile(... ;

并称为

contacts::readfile(...;

或者,如果您不需要直接访问类的内部结构,您可以在类外声明它(作为自由函数,类似于普通 C 函数)并完全按照您现在的方式使用。 这实际上是编译器在遇到您的代码时正在搜索的内容。

另外,我建议您重命名class contacts -> class contact因为每个对象似乎只包含 1 个人的联系信息。

我建议重构以使用 STL 向量。

#include <vector>
#include <ReaderUtil>

using namespace std;

vector< contact > myContactCollection;
myContactCollection.push_back( Contact("Bob",....) );
myContactCollection.push_back( Contact("Jack",....) );
myContactCollection.push_back( Contact("Jill",....) );

或者...

myContactCollection = ReaderClass::csvparser(myFile);

在哪里

ReaderClass::csvparser(std::string myFile) returns vector<Contact>

由于您的 readfile 函数位于contacts 类中,因此上面的答案在技术上是正确的,因为您需要创建对象的实例然后调用该函数。 但是,从 OO 的角度来看,您的类函数通常应该只对包含它的类的对象的成员进行操作。 您在这里拥有的更像是一个通用函数,它接受多种类型的参数,其中只有一个是指向本身包含您正在调用的函数的类的指针,如果您考虑一下,这有点奇怪。 因此,您会将指向该类的指针传递给该类的成员函数,这将需要它的两个实例。 您不能将类视为指向结构的指针的简单替代。 由于这是一个类,因此您将所有需要的变量声明为类的成员,因此无需将它们作为参数传递(类的要点之一是将一般数据与类成员数据隔离)。 这是一个更新,应该为您指明正确的方向。

   class contacts
     {
      private:

          char *First_Name;
          char *Last_Name;
          char *home;
          char *cell;
          FILE *read;  // these all could also be declared as a stack variable in 'readfile'


    public:
    //constructor

    contacts()
        {
        }  

    //destruction
    ~contacts()
    {
    }

    //Function declaration     
    int contacts::readfile (char * userEnteredFilename);

    };


    contacts myContact = new contacts();

    printf("Please enter a file name");
    scanf("%s",user_entry3); 

    int iCount = myContact->readfile(user_entry3);

    // the readfile function should contain all of the file i/O code 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM