C++ 使用函数指针重写纯虚函数

标签 c++ oop inheritance function-pointers virtual-functions

如果我有一个纯虚函数,可以用函数指针覆盖它吗?下面的场景(我知道它在语法上不是 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/

相关文章:

c++ - 未解析的外部符号 C++

c++ - MinGW下的Boost::Xpressive编译拼图

java - 在 Java 9 中使用必需参数和可选参数构建抽象父类(super class)的子类对象的最佳方法是什么?

multithreading - 对象方法的 Perl 线程

c# - 我可以创建一个 "global"对象来存储多个对象的变量吗?

java - 在 Java 中,如何从派生类中的覆盖方法调用基类的方法?

java - 将函数指针的 C 结构体转换为 JNA 代码

c++ - Arduino 错误 "unable to find a register to spill in class ' NO_REGS'”

java - 我可以将 ActionListener 添加到 jFrame 中的按钮并在不同的类中使用 actionPerformed 方法吗?

c# - 如何调用声明为抽象重写的基方法