简体   繁体   English

从child调用父方法,类似于调用“super”(C ++)

[英]Call a parent's method from child, similar to calling “super” (C++)

Is it possible to "reuse" a parent method in a child method and add functionality, just like with the super operator in Java? 是否可以在子方法中“重用”父方法并添加功能,就像在Java中使用super运算符一样?

parent.method(int a){
  a++;
}

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

I know that this is probably quite a basic question, sorry about that. 我知道这可能是一个非常基本的问题,抱歉。

I know I can just copy/paste the method to the child class and add the functionality there, by overloading; 我知道我可以将方法复制/粘贴到子类,并通过重载在那里添加功能; I'm looking for a more convenient way though. 我正在寻找一种更方便的方式。

You can use __super to do this, but it is a Microsoft extension. 您可以使用__super执行此操作,但它是Microsoft扩展。

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

Alternatively you can explicitly call the base implementation from the derived class: 或者,您可以从派生类显式调用基本实现:

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

You can invoke the parent member function in a child member function by qualifing the member function name with the name of the parent class: 您可以通过使用父类的名称限定成员函数名称来调用子成员函数中的父成员函数:

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

Yes, there is no super keyword, but you just give the name of the parent class instead. 是的,没有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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM