简体   繁体   中英

C++: call class method from a non-class function

I want to write a help function which calls a class method:

foo.h

class cls{
  public:
  void fun();
  void fun1();
};

foo.cpp

void cls::fun(){
  helperFun();
}

void helperFun(){
  fun1();//how to call fun1() here?
}

How should I do it, or what's the best way of doing it?

In order to call a method of cls you need to have a cls instance at hand. fun has access to this and can use it to provide helperFun with that instance:

void cls::fun(){
  helperFun(*this);
}

// If fun1() was const, the parameter could be a const cls&
void helperFun(cls& arg){
  arg.fun1();
}

This is only one (pretty direct) way of arranging things, there are more options in general and picking the best depends on what you are trying to do exactly.

It needs an instance of the class to be called on. Perhaps you want the instance to be the same as the one that fun is being called on. In which case, you could pass *this to helperFun :

void cls::fun(){
  helperFun(*this);
}

void helperFun(cls& obj){
  obj.fun1();
}

Pass helper function as argument to fun1:

void cls::fun(){
  helperFun(this); //currently passing as this pointer
}

void helperFun(cls* obj){
  obj->fun1();
}

A non-static class method, such as fun , is always called on an instance of its class. You need an instance of cls to call fun. You may get that instance in one of the following ways:

  • By creating a cls object inside the body of fun .
  • By passing a cls object (or a reference to it, or a pointer to it) as a parameter to fun (involves changing the signature of fun ).
  • By creating a global variable of type cls (I strongly discourage this option).

Alternatively, fun might be declared as static, provided that it does not use any filed of the cls class. In that case, you could invoke it without an associated instance of cls, with the following instruction: cls::fun() .

If you need a helper function that you call from one method of the class, and then it needs to call into another method of that same class, why don't you make it a member of the class? I mean, it cannot be a stand-alone method, it is tightly coupled with your class. So it must belong to the class, IMO.

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