简体   繁体   English

如何从父母 class 呼叫孩子 function

[英]How to call child function from parent class

For example i have例如我有

class A
{
  void Afunction();
};

and i have我有

#include "A.h"
class B: public A
{
   void Function();
   
};
    #include "B.h"
    class C
    {
       void UpdateStuff();
       void CreateStuff();
       B* Stuff;
    }

I need call CreateStuff();我需要调用CreateStuff(); from Afunction();来自Afunction(); but I can't just #include "Ch" Is there another way to do this?但我不能只是#include "Ch"还有其他方法吗?

You can call child function using a pointer or a reference of Parent class that points or references the child object. For example:您可以使用指向或引用子 object 的指针或父 class 的引用来调用子 function。例如:

#include <iostream>
struct A
{
   virtual void Function()                            //Defination
   { std::cout << "Super_class: A\n"; }
   virtual ~A() {}
};

struct B
{
   virtual void Function() { std::cout << "Child_class\n"; }
};

int main()
{
 A *obj1 = new B;
 obj1->Function();
 B obj2;
 obj2.A::Function();      //Calling to Parent class function(A)
 obj2.Function();         //Calling to Child class function(B)
}

You're unable to achieve that with your current code design.您无法通过当前的代码设计实现这一目标。 Class A does not inherit from Class C and Afunction() doesn't get passed a reference to Class C. Class A 没有继承自 Class C 并且Afunction()没有传递对 Class C 的引用。

You can either make A inherit C like you have with B inheriting A or you can pass a reference to the function like so您可以像 B 继承 A 那样让 A 继承 C,也可以像这样传递对 function 的引用

class A
{
  void Afunction(C* CObject);
};

Furthermore you also can't call child class functions from parent class functions when talking about inheritance. Inheritance works from Top down not from the bottom up.此外,在谈论 inheritance 时,您也不能从父 class 函数调用子 class 函数。Inheritance 从上到下而不是从下到上工作。

For example例如

class A
{
    void Afunction();
};

class B : public A
{
    void Afunction()
    {
        A::Afunction(); // This is valid
    }
}

This is not valid code.这不是有效代码。

class A
{
    void Afunction()
    {
        B::Afunction(); // This is not valid as A::Afunction() does not inherit from B::Afunction() 
    }

};

class B : public A
{
    void Afunction();
}

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

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