简体   繁体   中英

calling a class's non-static member from another class's static member

I have two classes;

encoder.h

#include "stationControl.h"

    public:
         static void getLocation();
         static stationControl *station1;
         static stationControl *station2;
         static stationControl *station3;
    private:
         static stationControl *stations[3];

encoder.cpp

#include "encoder.h"

stationControl *encoder::station1;
stationControl *encoder::station2;
stationControl *encoder::station3;

stationControl *encoder::stations[] = {encoder::station1,encoder::station2,encoder::station3};

void encoder::getLocation()
{
  *stations[1]->*stationControl::senarioControl(); // Here is the problematic line
}

stationControl.h

   public:      
      void (stationControl::*senarioControl)();
      void controlOut();

stationControl.cpp

#include "stationControl.h"

stationControl::stationControl()
{   
    senarioControl= &stationControl::controlOut;
}

void stationControl::controlOut()
{
     // some staffs...
}

  • I need static stationControl object in encoder.h
  • I need non-static controlOut function for every stationControl object (every function is special for its object)
  • I need to create a pointer for controlOut function as senarioControl
  • I need to call senarioControl pointer from encoder::getLocation

As on the code above in encoder.cpp (signed with "// Here is the problematic line" ), I got an error like;

invalid use of member 'stationControl::senarioControl' in static member function

senarioControl is a member of stations[1] , so you access it, like all members, as

stations[1]->senarioControl

Then you dereference it relative to stations[1] , remembering that you need parentheses:

stations[1]->*(stations[1]->senarioControl)

Then you call the function, and due to precedence rules you need another pair of parentheses:

(stations[1]->*(stations[1]->senarioControl))();

This is so unreadable that it's common to add another member that only calls through the function pointer:

class stationControl
{
    public:
        void callScenario() { (this->*senarioControl)(); }
        ...

so you can write the much more readable

stations[1]->callScenario();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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