Sef*_*efu 0 c++ pointers function-pointers function
我需要在另一个类中使用一个类中定义的函数.我尝试将函数作为指针传递,而不是重写整个函数,如下所示:
class C {
public:
int get(int x) { return x*x; }
};
struct S {
int (*func) (int x);
};
int main() {
C c;
S s;
cout << c.get(3) << endl;
s.func = &C::get;
cout << s.func(3) << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这不起作用,并给出以下错误:
func_ptr.cpp: In function ‘int main()’:
func_ptr.cpp:42:18: error: cannot convert ‘int (C::*)(int)’ to ‘int (*)(int)’ in assignment
Run Code Online (Sandbox Code Playgroud)
是否可以做这样的事情,如果是这样,我该如何解决?而且,如果可能的话,我可以使用来自对象实例而不是类的指针吗?也就是说,可能使用在特定类实例中定义的变量.谢谢.
C::get()是一个非静态成员函数,这意味着它必须在一个实例上调用C.它有一个隐含的第一个参数,this指针,在调用函数时必须传递给它.
由于您C::get()似乎不需要访问任何数据成员C,因此您可以将其作为static成员函数.
static int get(int x) { return x*x; }
Run Code Online (Sandbox Code Playgroud)
现在你的代码将按原样运行.
另一个选择是更改,func以便它是指向成员函数的指针C
struct S {
int (C::*func) (int x);
};
Run Code Online (Sandbox Code Playgroud)
并将其调用为
s.func = &C::get;
std::cout << (c.*(s.func))(3) << std::endl;
Run Code Online (Sandbox Code Playgroud)
另一个选择是改变的类型S::func来std::function<int(int)>.现在它可以保存任何可调用的(函数指针,函子,lambda),它将单个int作为参数,并返回一个int.
struct S {
std::function<int(int)> func;
};
s.func = std::bind(&C::get, &c, std::placeholders::_1);
std::cout << s.func(3) << std::endl;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
697 次 |
| 最近记录: |