将函数的引用设置为其他 c++ 文件中的非静态函数
Set reference of function to non-static function from other c++ file
我正在尝试在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...);
在这里,我提出了一个简单的演示,展示了我刚才所说的所有内容。
相关文章:
- .cpp和.h文件中的模板专用化声明
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 文本文件中的单词链表
- CMake-按正确顺序将项目与C运行时对象文件链接
- 使用新行和不使用新行读取文件
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 挂起和取消挂起一个文件DLL
- 如何确定我已使用非编码文件到达 EOF?
- 命名空间中具有.h和.cpp文件的类
- 如何使用ndk-build.cmd构建Android.so文件
- 从包含m行的文件中提取n行,必要时(惰性地)重复该文件
- 读取文件并输入到矢量中
- 在C++中查找文件
- c++库的公共头文件中应该包含什么
- 用c++从输入文件中读取另一行
- Cppcheck生成xml转储文件
- 读取文件的最后一行并输入到链接列表时出错
- 无法编译 rtmidi 测试 cmidiin.cpp 文件, 非法指令
- 如何将内容数组写入文本文件?
- C++ Windows 驱动程序MSB3030无法复制该文件,因为它找不到