简体   繁体   English

从库调用非虚拟成员函数

[英]Calling non-virtual member function from base

I'm about to desperate! 我快要死了! I need to call a non-virtual member function from a pointer to my base class: 我需要从指向我的基类的指针中调用一个非虚拟成员函数:

class A {  };

class B : public A { public: void evilFunction() { std::cout << "Yay!"; } };

int main(void) {
    A *pointer = new B();

    // Now do something like this: 
    // pointer->evilFunction();

    return 0;
}

I know I can do this with dynamic_cast - but I'm not allowed to! 我知道我可以使用dynamic_cast做到这一点-但我不允许这样做! I really have no idea what else I can do. 我真的不知道我还能做什么。 In theory, since I have the pointer, I'm pretty sure I can do some magic with pointer arithmetics to get the memory position of the function and then call it, but I don't know how to do this or at least how to start. 从理论上讲,因为有了指针,所以我很确定我可以使用指针算术做一些魔术,以获取函数的内存位置,然后调用它,但是我不知道该怎么做,或者至少不知道该怎么做。开始。

Any one who can give me a hint? 谁能给我提示? That's all I need. 这就是我所需要的。 Or I'm gonna use my epic beginner skills to write code to delete g++ in retaliation for the pain C++ is causing to me! 否则我将使用我的史诗般的初学者技能来编写代码以删除g ++,以报复C ++给我带来的痛苦! You can't let that happen, right?! 你不能让这种事情发生,对吧?

When you know that the pointer really points to a B , then just use a static_cast . 当您知道指针确实指向B ,只需使用static_cast


int main()
{
    A *pointer = new B();

    // Now do something like this: 
    // pointer->evilFunction();
    static_cast<B*>( pointer )->evilFunction();
}

The main question here, is why are you not allowed to use dynamic_cast. 这里的主要问题是为什么不允许您使用dynamic_cast。

If this is because you do not use RTTI, and you can still use static_cast - this may be your answer. 如果这是因为您不使用RTTI,但仍可以使用static_cast-这可能是您的答案。

However, if this is because of code-standard or alike, I would imagine that static_cast, or any "magic" would also be prohibited, and therefore, you will have to think of another solution (for example, making this method virtual, adding "manual typeid" to the base-class, and dispatching accordingly(hate this...), etc.) 但是,如果这是由于代码标准或类似原因引起的,我想也将禁止static_cast或任何“魔术”,因此,您将不得不考虑另一种解决方案(例如,将该方法虚拟化,添加“手动typeid”传递给基类,并进行相应的调度(讨厌这个……),等等)

如果不想使用虚函数的原因是避免使用RTTI,则可以使用CRTP习惯用法实现静态多态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM