首页 > 解决方案 > C++ 如何知道子类调用父方法?

问题描述

我不知道如何总结我的问题,所以在谷歌上找不到答案。

重写父方法时,

void Child::method(){
    //stuff
    Parent::method();
}

完美运行。但是父方法需要来自 Child 类实例的信息才能正常工作,这不是作为参数给出的。所以我的问题是,C++ 是否有一种机制让 Parent 知道 Child 类的哪个实例调用 Parent 方法,就像不做一样Parent::method(this)

让我想到的是,如果你做这样的事情,

int main(){
    SomeParentClass::someMethod();
}

它给出:错误:在没有对象参数的情况下调用非静态成员函数。所以编译器需要知道实例,子类中也没有给出。但没有引发错误,因此它必须知道该实例。

编辑:我添加了 Qt 标签,因为我正在尝试 Qt 类。这样我可以在需要时举一个例子。

编辑2:

设备对话框.h

class DeviceDialog : public QDialog
{
    Q_OBJECT

public:
    explicit DeviceDialog(QWidget *parent = nullptr);
    int exec() override;
    ~DeviceDialog() override;
}

设备对话框.cpp

int DeviceDialog::exec(){
    // My code.
    return QDialog::exec();
}

exec()函数激活并在屏幕上显示一个 QDialog。但是,以这种方式调用它,似乎父方法无法知道要显示哪个对话框(未传递参数)。唯一的知识可能是调用它的实例的身份。我只是问这些知识是否转移到后台的方法中。

标签: c++qtc++11inheritance

解决方案


This is nothing special to member functions of a parent class. Calling a function of the child class via explicitly naming the type:

Child::method();

works in exactly the same way in this regard. Used outside of a member functions definition it causes the same error.

The relevant paragraph of the standard is §9.3.1:

When an id-expression that is not part of a class member access syntax and not used to form a pointer to member is used in a member of class X in a context where this can be used, if name lookup resolves the name in the id-expression to a non-static non-type member of some class C, and if either the id-expression is potentially evaluated or C is X or a base class of X, the id-expression is transformed into a class member access expression using (*this) as the postfix-expression to the left of the . operator.

So, in other words, the call

Parent::method();

inside a member function is transformed into something akin to

(*this).Parent::method();

推荐阅读