C++ 有 super么?

本文探讨了C++中由于支持多重继承而未引入super关键字的原因。解释了如何通过使用父类作用域解析来调用特定基类的方法。

C++没有super 关键字,因为C++ 支持 多重继承,所以super无法获得 究竟 是那一个父类 的同名方法,数据!

父类::data/function


改为:

C++ does not have a keyword named `super` like some other object-oriented languages such as Java or Python. In languages that do have the `super` keyword, it is typically used to refer to the superclass of a subclass and is often used to call superclass constructors or methods that have been overridden in the subclass. In C++, the functionality provided by the `super` keyword in other languages is achieved through explicit calls to the base class constructor or methods using the scope resolution operator `::`. For example, if a derived class overrides a method from its base class, it can still invoke the base class's version of that method by qualifying the method call with the base class name followed by the scope resolution operator [^2]. Here is an example of how to explicitly call a base class constructor and method in C++: ```cpp #include <iostream> using namespace std; class Base { public: Base() { cout << "Base constructor called." << endl; } void show() { cout << "Base show function." << endl; } }; class Derived : public Base { public: Derived() : Base() { // Explicitly calling Base constructor cout << "Derived constructor called." << endl; } void show() { Base::show(); // Explicitly calling Base's show function cout << "Derived show function." << endl; } }; int main() { Derived d; d.show(); return 0; } ``` When the `Derived` class's `show` function is called, it first calls the `Base` class's `show` function using `Base::show();` before executing its own logic. This achieves the same purpose as the `super` keyword in other languages, even though the syntax is different. In summary, while C++ does not have a `super` keyword, the same functionality can be achieved by explicitly calling base class constructors and methods using the scope resolution operator `::` [^2].
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Farmwang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值