将函数的引用设置为其他 c++ 文件中的非静态函数

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

本文关键字:文件 c++ 静态函数 函数 引用 设置 其他      更新时间:2023-10-16

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

无法创建指向成员函数的非常量指针。

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

测试.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作为编译器。

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方法(本质上是一个"普通"函数(。

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

实际上正确的方法是:

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

这样,名为ptr_method的变量就是类test指针的方法。

然后

获取方法的地址。

您的陈述:

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

是完全错误的。类方法的地址是与该类的对象无关的东西。

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

&CLASS_NAME::METHOD_NAME;

事实上,该声明应该是这样的:

tc.update = &test::update;

其他建议。

通过方法指针调用方法。

有了方法指针后,调用与其关联的方法就不是那么直接了。 正如我之前所说,方法的地址与该类的对象无关,因此如果要调用该方法,则需要向编译器提供有关必须调用该方法的对象的信息。

语法类似于:

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

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