c++ - 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。但是,以这种方式调用它,似乎父方法无法知道要显示哪个对话框(未传递参数)。唯一的知识可能是调用它的实例的身份。我只是问这些知识是否转移到后台的方法中。
解决方案
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();
推荐阅读
- latex - 使用“visible on =”自动为 tikzpicture 设置动画
- java - Jackson 无法解析 POST 请求的正文
- flutter - 更改图像大小以在颤动的网格视图中获取整个单元格
- php - 在 php 7 中何时使用 self 而不是 $this?
- python - 有条件地删除 XML 元素
- iis - IIS Tomcat 连接器,AJP 配置
- amazon-web-services - AWS VPC 启用 DNS 解析:无法从公有子网读取内部终端节点
- python - 在熊猫数据框中第一次出现条件后删除所有行
- azure-data-explorer - 从 ADX 导出 1TB 数据
- python - 单元测试正则表达式以检查误报