21xrx.com
2025-07-12 03:23:56 Saturday
文章检索 我的文章 写文章
如何在C++中调用父类的同名方法
2023-07-06 11:49:50 深夜i     11     0
C++ 继承 同名方法 调用 父类

C++是一种面向对象的编程语言,其中父类和子类之间存在继承关系。在一些情况下,子类需要重写父类的方法,但是仍然需要保留父类的同名方法。这时候,就需要在子类中调用父类的同名方法。

在C++中,可以使用作用域解析运算符“::”来调用父类的方法。作用域解析运算符可以指定调用父类中的同名方法,而不是子类中重写的方法。

下面是一个示例代码:

#include <iostream>
using namespace std;
class Parent {
public:
  void print()
    cout << "This is the parent class." << endl;
  
};
class Child : public Parent {
public:
  void print() {
    cout << "This is the child class." << endl;
    Parent::print(); // 调用父类的同名方法
  }
};
int main() {
  Child child;
  child.print(); // 输出"This is the child class."和"This is the parent class."
  return 0;
}

在这个例子中,子类Child重写了父类Parent中的print()方法。在子类Child的print()方法中,使用“Parent::print()”调用了父类的同名方法,即输出"This is the parent class."。

除了使用作用域解析运算符外,还可以使用virtual和override关键字来实现调用父类的同名方法。在父类中将同名方法设为虚函数,在子类中使用override关键字重写同名方法,并在重写的方法中使用base关键字调用父类的同名方法。这种方法在多态的情况下更加灵活。

在调用父类的同名方法时,需要谨慎处理好继承关系和重写方法,避免出现错误或歧义。在合适的情况下,调用父类的同名方法可以提高代码的复用性和可维护性。

  
  

评论区