调用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();
。
"Menu"函数是否来自类contacts
?按照您的设计方式,它只能在类的实例上调用。您的选择完全基于readfile
对contacts
的含义
我猜函数读取所有联系人,而不仅仅是一个联系人,这意味着它可以成为静态函数
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
- "error: no matching function for call to"构造函数错误
- 什么时候调用组成单元对象的析构函数
- 继承函数的重载解析
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- C++模板来检查友元函数的存在
- 递归函数计算序列中的平方和(并输出过程)
- 对RValue对象调用的LValue ref限定成员函数
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 为什么使用 "this" 指针调用派生成员函数?
- 将对象数组的引用传递给函数
- 函数调用中参数的顺序重要吗
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用不带参数的函数访问结构元素
- 代码在main()中运行,但在函数中出现错误
- 内置函数可查看CPP中的成员变量
- 如何获取std::result_of函数的返回类型
- 如何在c++中为模板函数实例创建快捷方式
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗