繁体   English   中英

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

[英]C++ accessing a function from in a class, receiving functions as a parameter

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

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

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


//main.cpp

void function()
{
//stuff happens
}

有没有办法做到这一点? 还是我需要将此 function 添加到 class 以使其工作。 另外,您将如何 go 创建一个接收 function 作为参数的 function? 例如function(function2())

i am simply trying to access a function from a class as it would make my code easier to use later if the function that i am using doesn't get added to a class. 关于秒问题我创建一个接收时间的 function 和一个 function 作为参数。 它将等待指定的时间然后执行程序

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

1. 在另一个文件(翻译单元)中访问 class 成员函数:
显然,您需要在调用方翻译单元中包含 header 文件,该文件具有 class 声明。

示例代码:

//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.访问另一个文件中的免费功能(翻译单元):

You do not need to include the function in any class, just include the header file which declares the function and then use it in your translation unit.

示例代码:

//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 在评论中指出的另一种情况是:
header 文件中的声明,后跟仅在一个翻译单元中的定义

示例代码:

//Yourinclude File
void doSomething();  //declares the function

//Your another file
include"Yourinclude"
void doSomething()   //Defines the function
{
    //Something interesting
}

int main()
{
    doSomething();
    return 0;
}

或者,一种混乱的方法可能是在另一个文件中将 function 标记为 extern 并使用 function。不推荐,但有可能,所以这里是如何:

示例代码:

extern void doSomething();

int main()
{
    doSomething();
    return 0;
}

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

示例代码:

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


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


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

}

您需要一个您想要调用的 function 的原型。 class 主体包含其所有成员函数的原型,但独立函数也可以具有原型。 通常,您将这些组织在 header 文件中,该文件包含在包含 function 实现的文件中(以便编译器可以检查签名)和任何希望调用 ZC1C425268E68385D1AB5074F14ZA 的文件中。

(1) How can the `class` function be accessible ?

您需要在 header 文件中声明class主体,并在需要的地方#include 例如,

//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 ?

您可以使用指向 class成员函数的指针。

暂无
暂无

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

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