首页 > 解决方案 > 如何在c++中访问父类的函数并将变量保留在父类中?

问题描述

 //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();
    }

}

SystemEventHandlerImpl 类如何调用 camerafunction 类中的函数 detectcam() ,同时维护 camerafunction 类中的变量?

我已经尝试过 class SystemEventHandlerImpl : public camerafunction 但由于 camerafunction 变量发生变化而失败。

和变量SystemPtr系统,CameraList camList;CameraPtr pCam; 不能设置为静态。<< 未解析的外部符号

标签: c++class

解决方案


你在找protected吗?

注意:这是一个假设,因为这个问题对我来说并不完全清楚。如果要访问父类属性,则需要在 aprotectedpublic部分中声明它们。

这是一个示例:

#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;
}

在线运行: https ://onlinegdb.com/r1NyfgelO


推荐阅读