调用C++中的函数

calling functions in C++

本文关键字:函数 C++ 调用      更新时间:2023-10-16

我试图在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();

"Menu"函数是否来自类contacts?按照您的设计方式,它只能在类的实例上调用。您的选择完全基于readfilecontacts的含义

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

static void readfile(... ;

并以的身份呼叫

contacts::readfile(...;

或者如果你不需要直接访问类的内部,你可以在类之外声明它(作为一个自由函数,类似于普通的C函数),并像现在一样使用。事实上,当编译器遇到您的代码时,它就是在搜索这一点。

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

我建议重构以使用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