在派生类中分配基类函数指针

时间:2021-05-10 02:20:16

标签: c++ visual-c++ c++17

我有一个项目,其中有一个基类,其中包含未分配的函数指针数组。我创建了一个小代码示例,它基本上捕获了我想要做的事情:

const [showModalLog, setShowModalLog] = useState (true);

    const openModalLog = () => {
        setShowModalLog(prev => !prev)
    };

const [showModalReg, setShowModalReg] = useState (false);

    const openModalReg = () => {
        setShowModalReg(prev => !prev)
    };
  return (
    <div className="d-flex justify-content-end">
        <div className="text-center m-3">
            <button className="btn btn-link" type="button" onClick={openModalLog}>inicio</button>
            <ModalLog showModalLog={showModalLog} setShowModalLog={setShowModalLog}/>
        </div>
        <div className="text-center m-3">
            <button className="btn btn-dark" type="button" onClick={openModalReg}>registro</button>
            <ModalReg showModalReg={showModalReg} setShowModalReg={setShowModalReg}/>
        </div>
    </div>
)

有没有办法做我上面尝试做的事情,本质上是将 base_class 中的函数指针分配给派生类中匹配相同格式的函数?我怀疑不是,因为我们被迫创建指示类的模板,即 class base_class; class derived_class; using funcPtr = void (base_class::*)(); //using funcPtr2 = void (derived_class::*)(); <- I could use this instead, but the base class shouldn't know that the derived class exists... class base_class { public: void CustomBase() { cout << "Base class custom"; } funcPtr func1; funcPtr func2; }; class derived_class : public base_class { public: void CustomDerived() { cout << "Derived class custom"; } void SetupFuncPtrs() { func1 = &base_class::CustomBase; // <- This works (this->*func1)(); func2 = &derived_class::CustomDerived; // <- This generates C2064 (this->*func2)(); } }; ,但只是想知道是否有办法解决这个问题。

1 个答案:

答案 0 :(得分:0)

看来,我可以通过使用 reinterpret_cast<>

来实现我所需要的

即更改以下行:

func2 = &derived_class::CustomDerived;  // <-  This generates C2064

到:

func2 = reinterpret_cast<funcPtr>(&derived_class::CustomDerived);

在这种情况下,我是在“回答”我自己的问题。我绝不是在暗示这是最好的解决方案,也不是说设计本身是否是最好的,我只是指出了一种适用于我的特定场景的机制。

相关问题