如何解决C ++从类中访问函数,将函数作为参数接收
| 我有两个相当小且相关的问题,所以我将它们都放在同一个问题中。 我一直在尝试使用类,并且例如尝试访问不在类中的另一个文件中的类。//class 1 .cpp
void Class1::function1()//another error
{
function()
}
//main.cpp
void function()
{
//stuff happens
}
有没有办法做到这一点?还是我需要将此功能添加到类中才能使其正常工作。您还将如何创建一个以函数形式接收函数的函数?例如function(function2())
我只是尝试从类访问函数,因为如果我使用的函数没有添加到类中,这将使以后的代码更易于使用。关于秒数问题i,后者创建了一个接收时间的函数和一个函数作为自变量。它将等待指定的时间,然后执行程序
解决方法
如何访问另一个文件中的功能?
取决于功能的类型,可能有以下几种情况:
1.在另一个文件(翻译单元)中访问类成员函数:
显然,您需要包括头文件,该文件在呼叫者翻译单元中具有类声明。
示例代码:
//MyClass.h
class MyClass
{
//Note that access specifier
public:
void doSomething()
{
//Do something meaningful here
}
};
#include\"MyClass.h\" //Include the header here
//Your another cpp file
int main()
{
MyClass obj;
obj.doSomething();
return 0;
}
2.访问另一个文件(翻译单元)中的免费功能:
您不需要在任何类中包含该函数,只需包含声明该函数的头文件,然后在翻译单元中使用它即可。
示例代码:
//YourInclude.h
inline void doSomething() //See why inline in @Ben Voight\'s comments
{
//Something that is interesting hopefully
}
//Your another file
#include\"YourInclude.h\"
int main()
{
doSomething()
return 0;
}
@Ben在注释中指出的另一种情况可以是:
头文件中的声明,后跟一个翻译单元中的定义
示例代码:
//Yourinclude File
void doSomething(); //declares the function
//Your another file
include\"Yourinclude\"
void doSomething() //Defines the function
{
//Something interesting
}
int main()
{
doSomething();
return 0;
}
另外一种麻烦的做法是将功能标记为另一个文件中的extern并使用该功能。不建议这样做,但可以这样做:
示例代码:
extern void doSomething();
int main()
{
doSomething();
return 0;
}
您将如何创建一个将函数作为参数接收的函数?
通过使用function pointers
简而言之,函数指针不过是指针,而是保存函数地址的指针。
示例代码:
int someFunction(int i)
{
//some functionality
}
int (*myfunc)(int) = &someFunction;
void doSomething(myfunc *ptr)
{
(*ptr)(10); //Calls the pointed function
}
, 您需要要调用的函数的原型。类主体包含其所有成员函数的原型,但是独立函数也可以具有原型。通常,将它们组织在一个头文件中,该头文件包含在包含函数实现的文件中(以便编译器可以检查签名),并包含在希望调用该函数的任何文件中。
, (1) How can the `class` function be accessible ?
您需要在头文件中声明“ 9”主体,并在需要的地方声明“ 10”。例如,
//class.h
class Class1 {
public: void function1 (); // define this function in class.cpp
};
现在#include
到main.cpp
#include\"class.h\"
您可以在main.cpp中使用function1
。
(2) How to pass a function of class as parameter to another function ?
您可以使用指向类成员函数的指针。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。