我想创建一个类,它具有指向其某个方法的指针作为属性。然后应该有一个方法,用于设置这个指针。
class A {
private:
void (A::*curr_f)();
public:
void set(void (A::*f)()) {
curr_f = f;
}
};
当我尝试创建继承的类并将指针设置为其方法之一时,问题就开始了。
class B : A {
public:
void main() {
set(&B::new_function);
};
void new_function() {};
};
我得到的错误非常简单,但我仍然不知道如何解决这个问题。
error: no matching function for call to ‘B::set(void (B::*)())’
note: candidate is:
note: void A::set(void (A::*)())
note: no known conversion for argument 1 from ‘void (B::*)()’ to ‘void (A::*)()’
答案 0 :(得分:6)
你做不到。 A
没有方法new_function
而且您对编译器撒谎。你有三种方式
将new_function
移至A
并传递A::new_function
(首选virtual
)。
class A
{
void (A::*curr_f)();
public:
void set(void (A::*f)())
{
curr_f = f;
}
virtual void new_function() {};
};
class B : A
{
public:
void main()
{
set(&A::new_function);
};
void new_function() {};
};
转发B
声明并将B::*
存储在A
:
class B;
class A
{
void (B::*curr_f)();
public:
void set(void (B::*f)())
{
curr_f = f;
}
};
class B : A
{
public:
void main()
{
set(&B::new_function);
}
void new_function() {}
};
您可以尝试基于模板的方式,例如the curiously recurring template pattern (CRTP)。
template <typename D>
class A
{
void (D::*curr_f)();
public:
void set(void (D::*f)())
{
curr_f = f;
}
};
class B : public A<B>
{
public:
void main()
{
set(&B::new_function);
}
void new_function() {}
};
答案 1 :(得分:0)
You can have the code like this:
#include <iostream>
using namespace std;
template<class T>
class A {
protected:
void (T::*curr_f)();
public:
virtual void set(void (T::*f)()) {
curr_f = f;
cout<<"Set in A"<<endl;
T obj;
(obj.*curr_f)();
}
virtual void new_function() {cout<<"in A"<<endl;};
};
class B :public A<B> {
public:
void func() {
set(&B::new_function);
};
void new_function() {cout<<"in B"<<endl;};
};
int main()
{
B obj;
obj.func();
}