我正在尝试在 C++ 中设置非静态函数的引用。我引用的函数不是来自同一个 c++ 文件,我得到错误提示:
无法创建指向成员函数的非常量指针。
主文件
#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;
}
测试.hpp
#ifndef Test_hpp
#define Test_hpp
#include <stdio.h>
class test {
public:
void update() {
//Do something
}
};
#endif /* Test_hpp */
我的问题是如何在不将测试类中的更新设置为静态的情况下做到这一点?
static void update() {
//Do something
}
使用此代码它可以工作,但就像我说过的那样,我不希望这个函数是静态的。
编辑: 因为我很愚蠢,所以我没有提到班级测试应该能够有所不同。同样对于我已经得到的答案,我了解到 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 作为编译器。