如果我有一个纯虚函数,可以用函数指针覆盖它吗?下面的场景(我知道它在语法上不是 100% 正确):
#include<iostream>
using namespace std;
class A {
public:
virtual void foo() = 0;
};
class B : public A {
public:
B() { foo = &B::caseOne; }
void caseOne() { cout << "Hello One" << endl; }
void caseTwo() { cout << "Hello Two" << endl; }
void (B::*foo)();
void chooseOne() { foo = &B::caseOne; }
void chooseTwo() { foo = &B::caseTwo; }
};
int main() {
B b;
b.(*foo)();
}
编辑:如果有人感兴趣,以下是我完成我想做的事情的方法:
#include<iostream>
using namespace std;
class A {
public:
virtual void foo() = 0;
};
class B : public A {
public:
B() { f = &B::caseOne; }
void caseOne() { cout << "Hello One" << endl; }
void caseTwo() { cout << "Hello Two" << endl; }
void (B::*f)();
void chooseOne() { f = &B::caseOne; }
void chooseTwo() { f = &B::caseTwo; }
void foo() { (this->*f)(); }
};
int main() {
B b;
b.foo();
b.chooseTwo();
b.foo();
}
输出为:
Hello One
Hello Two
最佳答案
没有。而你用错了这个。在您的代码中,您尝试将成员函数指针分配给函数指针 - 它无法编译。
C++03 标准 10.3/2
If a virtual member function vf is declared in a class Base and in a class Derived, derived directly or indirectly from Base, a member function vf with the same name and same parameter list as Base::vf is declared, then Derived::vf is also virtual (whether or not it is so declared) and it overrides Base::vf.
关于C++ 使用函数指针重写纯虚函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14641121/