指向类组合中成员函数的指针
Pointer to Member Function in Class Composition
我有两个类,Foo
和Bar
。类Foo
包含称为b
的类Bar
的实例,并且类Bar
需要访问类Foo
的成员函数FooFunc
。函数FooFunc
执行一些算术运算,但目前我只想尝试通过它,但我似乎无法使以下MWE(名为scratch.cpp
)工作:
#include <iostream>
class Foo; // forward declaration
class Bar
{
public:
Bar() {}
void BarFunc(double (Foo::*func)(double))
{
std::cout << "In BarFunc n";
}
};
class Foo // must be declared after Bar, else incomplete type
{
public:
Foo() {}
Bar b;
double FooFunc(double x)
{
return x + 1;
}
void CallBarFunc()
{
b.BarFunc(FooFunc); // error occurs here
}
};
int main()
{
Foo f;
f.CallBarFunc();
}
我得到的错误是
scratch.cpp:27:22: error: no matching function for call to ‘Bar::BarFunc(<unresolved overloaded function type>)’
scratch.cpp:27:22: note: candidate is:
scratch.cpp:9:8: note: void Bar::BarFunc(double (Foo::*)(double))
scratch.cpp:9:8: note: no known conversion for argument 1 from ‘<unresolved overloaded function type>’ to ‘double (Foo::*)(double)’
与衰减为函数指针的非成员函数不同,非static
成员函数不会衰减为指针。
代替:
b.BarFunc(FooFunc);
用途:
b.BarFunc(&Foo::FooFunc);
相关文章:
- QMetaObject invokeMethod的基于函数指针的语法
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- c++r值引用应用于函数指针
- 模板函数指针和lambda
- 是否可以将llvm::FunctionType转换为C/C++原始函数指针
- 带有类的函数指针
- () 函子后面的括号,而不是函数指针?
- 全局作用域中函数指针的赋值
- 使用"Task"函数指针队列定义作业管理器
- 将成员函数指针作为参数传递给模板方法
- 如何创建对象函数指针C++映射?
- 匹配函数指针作为模板参数?
- 通过函数指针定义类范围之外的方法
- 存储在类中的函数指针
- C++从函数指针数组调用函数
- 将返回值存储在函数指针数组的指针中是如何工作的?
- 整数键映射到头文件中的成员函数指针
- 从类成员函数到类 C 函数指针的转换
- 如何将内联匿名函数分配给C++函数指针
- 将字符缓冲区强制转换为函数指针