C++ 如何从派生类函数调用父类函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/357307/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 14:53:22  来源:igfitidea点击:

How to call a parent class function from derived class function?

c++oopinheritance

提问by IaCoder

How do I call the parent function from a derived class using C++? For example, I have a class called parent, and a class called childwhich is derived from parent. Within each class there is a printfunction. In the definition of the child's print function I would like to make a call to the parents print function. How would I go about doing this?

如何使用 C++ 从派生类调用父函数?例如,我有一个名为 的类parent,以及一个child从父级派生的名为 的类。每个类中都有一个print函数。在孩子的打印功能的定义中,我想调用父母的打印功能。我该怎么做呢?

回答by Motti

I'll take the risk of stating the obvious: You call the function, if it's defined in the base class it's automatically available in the derived class (unless it's private).

我将冒着风险说明显而易见的事情:您调用该函数,如果它是在基类中定义的,则它在派生类中自动可用(除非它是private)。

If there is a function with the same signature in the derived class you can disambiguate it by adding the base class's name followed by two colons base_class::foo(...). You should note that unlike Java and C#, C++ does nothave a keyword for "the base class" (superor base) since C++ supports multiple inheritancewhich may lead to ambiguity.

如果派生类中存在具有相同签名的函数,您可以通过添加基类名称后跟两个冒号来消除歧义base_class::foo(...)。你应该注意到,不像Java和C#,C ++并没有对“基础类”(关键字superbase),因为C ++支持多重继承,这可能导致歧义。

class left {
public:
    void foo();
};

class right {
public:
    void foo();
};

class bottom : public left, public right {
public:
    void foo()
    {
        //base::foo();// ambiguous
        left::foo();
        right::foo();

        // and when foo() is not called for 'this':
        bottom b;
        b.left::foo();  // calls b.foo() from 'left'
        b.right::foo();  // call b.foo() from 'right'
    }
};

Incidentally, you can't derive directly from the same class twice since there will be no way to refer to one of the base classes over the other.

顺便说一下,你不能直接从同一个类派生两次,因为没有办法引用一个基类而不是另一个基类。

class bottom : public left, public left { // Illegal
};

回答by Greg Hewgill

Given parent class named Parentand child class named Child, you can do something like this:

给定父类 namedParent和子类 named Child,您可以执行以下操作:

class Parent {
public:
    virtual void print(int x);
}

class Child : public Parent {
    void print(int x) override;
}

void Parent::print(int x) {
    // some default behavior
}

void Child::print(int x) {
    // use Parent's print method; implicitly passes 'this' to Parent::print
    Parent::print(x);
}

Note that Parentis the class's actual name and not a keyword.

请注意,这Parent是类的实际名称,而不是关键字。

回答by Andrew Rollings

If your base class is called Base, and your function is called FooBar()you can call it directly using Base::FooBar()

如果您的基类被调用Base,并且您的函数被调用,FooBar()您可以直接使用Base::FooBar()

void Base::FooBar()
{
   printf("in Base\n");
}

void ChildOfBase::FooBar()
{
  Base::FooBar();
}

回答by Andrey

In MSVC there is a Microsoft specific keyword for that: __super

在 MSVC 中有一个 Microsoft 特定的关键字:__super



MSDN: Allows you to explicitly state that you are calling a base-class implementation for a function that you are overriding.

MSDN:允许您明确声明您正在为要覆盖的函数调用基类实现。

// deriv_super.cpp
// compile with: /c
struct B1 {
   void mf(int) {}
};

struct B2 {
   void mf(short) {}

   void mf(char) {}
};

struct D : B1, B2 {
   void mf(short) {
      __super::mf(1);   // Calls B1::mf(int)
      __super::mf('s');   // Calls B2::mf(char)
   }
};


回答by Ajay yadav

If access modifier of base class member function is protected OR public, you can do call member function of base class from derived class. Call to the base class non-virtual and virtual member function from derived member function can be made. Please refer the program.

如果基类成员函数的访问修饰符是protected 或public,则可以从派生类调用基类的成员函数。可以从派生成员函数调用基类非虚和虚成员函数。请参考程序。

#include<iostream>
using namespace std;

class Parent
{
  protected:
    virtual void fun(int i)
    {
      cout<<"Parent::fun functionality write here"<<endl;
    }
    void fun1(int i)
    {
      cout<<"Parent::fun1 functionality write here"<<endl;
    }
    void fun2()
    {

      cout<<"Parent::fun3 functionality write here"<<endl;
    }

};

class Child:public Parent
{
  public:
    virtual void fun(int i)
    {
      cout<<"Child::fun partial functionality write here"<<endl;
      Parent::fun(++i);
      Parent::fun2();
    }
    void fun1(int i)
    {
      cout<<"Child::fun1 partial functionality write here"<<endl;
      Parent::fun1(++i);
    }

};
int main()
{
   Child d1;
   d1.fun(1);
   d1.fun1(2);
   return 0;
}

Output:

输出:

$ g++ base_function_call_from_derived.cpp
$ ./a.out 
Child::fun partial functionality write here
Parent::fun functionality write here
Parent::fun3 functionality write here
Child::fun1 partial functionality write here
Parent::fun1 functionality write here

回答by Dean P

Call the parent method with the parent scope resolution operator.

使用父作用域解析运算符调用父方法。

Parent::method()

父::方法()

class Primate {
public:
    void whatAmI(){
        cout << "I am of Primate order";
    }
};

class Human : public Primate{
public:
    void whatAmI(){
        cout << "I am of Human species";
    }
    void whatIsMyOrder(){
        Primate::whatAmI(); // <-- SCOPE RESOLUTION OPERATOR
    }
};

回答by superbem

struct a{
 int x;

 struct son{
  a* _parent;
  void test(){
   _parent->x=1; //success
  }
 }_son;

 }_a;

int main(){
 _a._son._parent=&_a;
 _a._son.test();
}

Reference example.

参考示例。