C++从类中访问函数,接收函数作为参数

标签 c++ function

我有两个相当小且相关的问题,所以我将它们放在同一个问题中。

我一直在试验类,例如,我试图访问不在类中的另一个文件中的类。

//class 1 .cpp
void Class1::function1()//another error 
{
    function()
}


//main.cpp

void function()
{
//stuff happens
}

有办法吗?或者我需要将这个函数添加到一个类中才能让它工作吗?另外,您将如何着手创建一个接收参数函数的函数?例如 function(function2())

我只是想从一个类中访问一个函数,因为如果我正在使用的函数没有被添加到一个类中,它会让我的代码更容易在以后使用。关于第二个问题,我要创建一个接收时间和函数作为参数的函数。它将等待指定的时间然后执行程序

最佳答案

如何访问另一个文件中的函数?
取决于函数的类型,可能有以下情况:

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;
}

您将如何创建一个接收函数作为参数的函数?
通过使用函数指针 简而言之,函数指针只不过是保存函数地址的指针。

示例代码:

int someFunction(int i)
{
    //some functionality
}


int (*myfunc)(int) = &someFunction;


void doSomething(myfunc *ptr)
{
    (*ptr)(10); //Calls the pointed function

}

关于C++从类中访问函数,接收函数作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6234300/

相关文章:

c++ - MFC 全局键盘 Hook

jquery - 基于 Modernizr : click vs hover 的不同方法

python - 链表 : How to remove odd numbers?

c++ - 在 C++ 中,如何对提供指针的函数返回的值进行操作?

c++ - 枚举和函数

c++ - 带有 std::map 错误函数调用的 boost::factory

c# - 将 char*[] 从 c++ dll 结构传递到 c#

c++ - C++ 中的函数重载(const 指针)

c++ - 更好的 C++ HTTP 客户端库

c++ - 在函数 c++ 中更改给定的函数参数