将函数引用设置为来自其他 C++ 文件的非静态函数

Set reference of function to non-static function from other c++ file

我正在尝试在 C++ 中设置非静态函数的引用。我引用的函数不是来自同一个 c++ 文件,我收到错误消息:

Cannot create a non-constant pointer to member function.

Main.cpp

#include <iostream>
#include "Test.hpp"

class testClass {
public:
    void (*update) (void);
};

int main() {
    testClass tc;
    test t;
    tc.update = &t.update; //This is where the error occurs
    return 0;
}

Test.hpp

#ifndef Test_hpp
#define Test_hpp

#include <stdio.h>

class test {
public:
    void update() {
        //Do something
    }
};

#endif /* Test_hpp */

我的问题是,如果不将测试 class 中的更新设置为静态,您如何做到这一点?

static void update() {
    //Do something
}

使用此代码可以正常工作,但正如我所说,我不希望此功能是静态的。

编辑: 因为我很笨,所以我没有提到 class 测试应该能够有所不同。对于我已经得到的答案,我还了解到 tc.update = &t.update;是错的。

例如:

#include <iostream>
#include "Test.hpp"
#include "anotherTestClass.hpp"

//I do not want to use templates if possible
class testClass {
public:
    void (*update)(void);
};

int main() {
    testClass tc;
    test t;
    tc.update = &test.update; //I know this is wrong now.
    testClass tc2;
    anotherTestClass atc;
    tc2.update = &atc.update;
    //p.s. I'm bad with c++
}

我现在得到的错误是。

Assigned to 'void (*)()' from incompatible type 'void (test::*)()'

还有一件事是我正在使用 XCode 进行编程,我相信它使用 LLVM-GCC 4.2 作为编译器。

class test {
public:
    void update() {
        //Do something
    }
};

class testClass {
public:
    void (test::* update) (void);
};

int main() {
    testClass tc;
    test t;
    tc.update = &test::update; 
    return 0;
}

你的方法本质上是错误的。

成员函数指针。

testClass中的成员:

void (*update) (void);

是一个函数指针,它不同于方法函数指针。这就是为什么为了编译你应该切换到 static 方法(本质上是一个“正常”函数)。

方法函数指针应该包含有关class方法所属的静态信息。

实际上正确的方法是:

void (test::* ptr_method)(void);  // a member pointer to test class

这样,名为ptr_method 的变量是class test 指针的一个方法。

然后,

获取方法的地址。

您的声明:

tc.update = &t.update; //This is where the error occurs

完全错了。 class 方法的地址与 class 的对象无关。

您可以使用以下语法获取方法的地址:

&CLASS_NAME::METHOD_NAME;

确实,该语句应该是这样的:

tc.update = &test::update;

其他建议。

通过方法指针调用方法。

一旦有了方法指针,就不会立即调用与其关联的方法。 正如我之前所说,方法的地址与那个 class 的对象无关,所以如果你想调用这个方法,你需要向编译器提供有关该方法必须访问的对象的信息被调用。

语法类似于:

(OBJECT.*METHOD_POINTER)(ARGS...);

Here,我提出一个简单的演示,它展示了我刚才所说的所有内容。