给出以下简单代码:
namespace exercise {
class A {
public:
virtual void a() = 0;
virtual void b() = 0;
virtual void c() = 0;
};
class B : public A {
void a() { std::cout << "a function @ B class"; }
void b() { std::cout << "b function @ B class"; }
void c() { std::cout << "c function @ B class"; }
};
class C : public A {
void a() { std::cout << "a function @ C class"; }
void b() { std::cout << "b function @ C class"; }
void c() { std::cout << "c function @ C class"; }
};
using Pstd_mem = void(A::*)();
void foo(A* basePointer, Pstd_mem action) {
basePointer->*action();
}
}
int main(void) {
using namespace exercise;
A* b = new B();
A* c = new C();
foo(b, &A::b);
}
我只是尝试使用函数foo通过指向成员函数的指针调用函数B(),但编译器在行上给出了错误:
basePointer->*action();
我做错了什么?
感谢
答案 0 :(得分:9)
错误:必须使用'。'或' - &gt; '在'action(...)'中调用指向成员的函数,例如'(... - &gt; *动作)(...)'
basePointer->*action();
所以,只需这样做:
(basePointer->*action)();