Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
231 views
in Technique[技术] by (71.8m points)

how to access function of parent class in c++ and keep the variable in parent class?

 //in GUI.h
class MFCGUI : public camerafunction
{   MFCGUI(){  startdevicevent();    }
    
}

// in camerafunction.h contain both class camerafunction and 
// class systemeventhandler

class SystemEventHandlerImpl;
class camerafunction 
    {
          public :
          void startdeviceevent () 
         {
                system = System::GetInstance();
                systemEventHandler = new SystemEventHandlerImpl(system);
                detectcam();

         }
         void detectcam()
         {
                camList = system->GetCameras(); // null ptr here when called 
                                               // from SystemEventHandlerImpl
         }

       SystemEventHandlerImpl *systemEventHandler;
      SystemPtr system;
      CameraList camList;
      CameraPtr pCam;        .....
   } 

class SystemEventHandlerImpl :public camerafunction
{
   void onDeviceArrival()
    {
     detectcam();
    }

}

how does class SystemEventHandlerImpl call the function detectcam() in class camerafunction while maintaining the variable in class camerafunction ?

i have tried class SystemEventHandlerImpl : public camerafunction but failed as camerafunction variables changes.

and variables SystemPtr system, CameraList camList; CameraPtr pCam; cannot be set as static . << unresolved external symbol

question from:https://stackoverflow.com/questions/65932850/how-to-access-function-of-parent-class-in-c-and-keep-the-variable-in-parent-cl

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Are you looking for protected ?

Note: this is a supposition, as the question is not completely clear to me. If you want to access parent class properties, they need to be declared in a protected or public section.

Here is a sample:

#include <iostream>

class camerafunction 
{
protected:
    int systemEventHandler=0;
public:
    void detectcam()
    {
        std::cout << "detectcam"<< std::endl;
    };
};


class MFCGUI : public camerafunction 
{
public:
    void startdeviceevent()
    {
        systemEventHandler = 42;
         std::cout << "startdeviceevent with systemEventHandler=" << systemEventHandler << std::endl;
    }
  
};

class SystemEventHandlerImpl
{
public:
    void onDeviceArrival()
    {
        MFCGUI obj;
        obj.startdeviceevent();
        obj.detectcam();
    }

};


int main()
{
    SystemEventHandlerImpl obj;
    obj.onDeviceArrival();

    return 0;
}

Run it online: https://onlinegdb.com/r1NyfgelO


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...