18

这个问题很相似,但是是关于从类内部调用函数:如果我要覆盖它,我可以调用基类的虚函数吗?

在这种情况下,您将指定Base::function()而不是function(),这将调用被覆盖的定义。

但是有没有办法在课堂之外做到这一点?我的类没有定义复制构造函数,所以我不知道如何转换为基类:

Base( derived_object ).function()

在这里做的适当的事情是 cast & derived_objectasBase*然后调用->function()吗?

感谢您的洞察力。

4

3 回答 3

25

尝试derived_object.Base::function();

于 2013-01-12T00:08:11.023 回答
11

我相信语法:

derived_ptr->Base::function();

工作得很好。虽然我真的质疑你为什么要在一个不属于你的类的函数中这样做。特别是如果function碰巧是一个虚函数。

这是一个有问题的想法的原因是,您所做的任何使用该表示法的东西都取决于您的类的继承层次结构。此外,函数通常被重写是有原因的。你可以通过使用这种语法来解决这个问题。

于 2013-01-12T00:03:40.133 回答
0

You probably want to use pointers to member functions of a class. Those give you the ability to map different base class functions to the pointer as needed, and the ability to use it as a variable or function parameter.

The syntax for a pointer to a member function looks like

class Base
{
public:
    virtual bool Function();
    virtual bool OtherFunction();
};

typedef bool (Base::*)() BaseFunc;

The list of caveats for using these things is a mile long- there is plenty online on how to use them (most of the answers are "don't"). However, they do give you a way of clearly binding to and calling a base class member function.

于 2013-01-12T04:27:40.597 回答