指针指向C 中的类方法
Pointer to a class method in c++
A有很多B类,A类具有一个对象b。该对象b具有一个函数(calc),需要在A的对象中指向方法的指针。此方法(有趣的)ACESS私有变量(在我的示例中,只需返回3)。
class A;
class B {
public:
virtual int calc ( int (A::*fun)()) { return 2*fun(); };
};
class A {
B* b;
public:
A (B* b_) : b (b_) {};
int fun() { return 3; };
int run(){ return b->calc(&A::fun); };
};
int main() {
B* b = new B();
A a(b);
a.run();
return 0;
}
在B类中的calc
方法的定义中,如何正确使用指针?
我收到此错误消息:
teste.cpp:10:58: error: must use ‘.*’ or ‘->*’ to call pointer-to-member function in ‘fun (...)’, e.g. ‘(... ->* fun) (...)’
virtual int calc ( int (A::*fun)()) { return 2*fun(); };
^
如果对您来说是可行的,建议使用std::function
方法。但是,为了完整,您将如何正确使用指针到会员功能。
指针到会员本身不会存储A
的"当前"实例,因此您需要明确传递该实例。然后,您使用特殊->*
(或.*
)语法来调用它。
virtual int calc (A* value, int (A::*fun)()) {
return 2 * (value->*fun)();
};
然后您将其称为b->calc(this, &A::fun);
。
您可以按照自己的方式进行操作,但是必须在特定实例上调用成员函数:
class A;
class B {
public:
virtual int calc(A* a, int (A::*fun)()) { return 2 * (a->*fun)(); };
};
class A {
B* b;
public:
A(B* b_) : b(b_) {};
int fun() { return 3; };
int run() { return b->calc(this, &A::fun); }; // now also passing this pointer
};
int main() {
B* b = new B();
A a(b);
a.run();
return 0;
}
如果您可以在没有calc()
的情况下生活,那么Lambda也是一个选择:
class A;
class B {
public:
template<typename T>
int calc(T fun) { return 2 * fun(); };
};
class A {
B* b;
public:
A(B* b_) : b(b_) {};
int fun() { return 3; };
int run() {
return b->calc([this]() {return fun(); } );
};
};
int main() {
B* b = new B();
A a(b);
a.run();
return 0;
}
将指针到类方法定义为(假设某些fn匹配签名):
):RetType (ClassName::*pfn)(Args) = &ClassName::SomeFn;
,称为:
ClassName * ptr = GetClassPtr();
(ptr->*pfn)(arg, arg);
如果您能够使用C 11,则应使用std :: function and std :: bind:否则您需要使用指针来成员函数 一个指针实例。
带有C 11
#include <functional>
class B {
public:
virtual int calc (std::function<int()>&& fun) { return 2 * fun(); }; };
};
class A {
B* b;
public:
A (B* b_) : b (b_) {};
int fun() { return 3; };
int run() { return b->calc(std::bind(&A::fun, this)); };
};
没有C 11
class B {
public:
virtual int calc (int(A::*fnptr)(), A* a) { return 2 * (a->*fnptr)(); };
};
class A {
B* b;
public:
A (B* b_) : b (b_) {};
int fun() { return 3; };
int run() { return b->calc(&A::fun, this); };
};
请参见此处的示例。
相关文章:
- 如何访问由共享指针保存的类方法?
- 我无法使用C++指针指向类方法返回的 std::vector
- 如何在成为指向基类的指针后保留对子类方法的使用?
- 将一个类的方法指针存储到另一个类中
- 如果类"A"具有指向另一个类的指针,则"B" A 可以访问 B 类公共方法
- 类方法返回指向具有模板的类成员的指针
- 指向类方法调用的指针
- 在类方法中使用 "this" 指针是否是一种好的做法?
- C++ - 类方法函数指针unordered_map的初始化器列表
- 如何定义和设置指向模板类方法的功能指针
- 如何在没有虚拟方法的类dynamic_cast指针?
- 将指针传递到类方法
- C++ - 基类函数指针调用的替代方法
- 将const指针(EVP_MD)保存到变量中,以将其重新使用为类方法(HMAC)
- 如何调用返回类方法指针的类方法
- C++;类方法指针;λ;将 lambda 作为成员函数指针传递;
- 尝试获取类方法指针时出现E_NOINTERFACE
- 指向方法父参数c++的子类方法指针
- 给出一个闭包作为"类方法指针"?
- 静态类方法指针数组的正确语法