从子级调用父级的方法,类似于调用"super" (C++)

Call a parent's method from child, similar to calling "super" (C++)

本文关键字:调用 super C++ 类似于 方法      更新时间:2023-10-16

是否可以像Java中的超级运算符一样,在子方法中"重用"父方法并添加功能?

parent.method(int a){
  a++;
}
child.method(int a /*would be nice w/out*/){
  printf("%d",a);
}

我知道这可能是一个很基本的问题,很抱歉。

我知道我可以通过重载将方法复制/粘贴到子类并在那里添加功能;不过,我正在寻找一种更方便的方式。

您可以使用__super来完成此操作,但它是Microsoft的扩展。

void CChild::function( int nParam )
{
    __super::function( nParam );
}

或者,您可以从派生类显式调用基本实现:

void CChild::function( int nParam )
{
    CParent::function( nParam );
}

您可以通过用父类的名称限定成员函数名称来调用子成员函数中的父成员函数:

void child::method()
{
    parent::method();
}

是的,没有super关键字,但您只提供父类的名称。

int child::method(int a ){ 
  // call base class
  int i = parent::method(a);
  printf("%d",a); 
} 
parent.method(int a){
  a++;
}
child::method(int a /*would be nice w/out*/){
  printf("%d",a);
  parent::method(a);
}