简体   繁体   中英

What is the correct way to encapsulate helper functions in C++?

Given a class:

class myClass{
// ...

private:
   int helperFuncForA();
   int secondhelperFuncForA();
public:
   void A();

// ...
};

Suppose that the helper functions are not used outside of A ; how do I encapsulate them such that calling them outside of A is impossible? Do I do:

class myClass{
// ...

public:
   class {
   private:
      int helperFuncForA();
      int secondhelperFuncForA();
   public:
      void call();
   } A;

// ...
};

and then call by writing:

myClass obj;
obj.A.call();

? Perhaps, I could overload A 's () operator instead of making the call() function for convenience. What is the correct way?

The correct way is using of lambdas:

class myClass{
// ...

private:
   // remove from here 
   //int helperFuncForA();
   //int secondhelperFuncForA();
public:
   void A();

// ...
};

// somewhere
void myClass::A()
{
   auto helperFuncForA = [this]() -> int
   {
      //...
      return 1;
   };

   auto secondhelperFuncForA = [this]() -> int
   {
      //...
      return 2;
   };

   //...
   int x = helperFuncForA(); 

   x += secondhelperFuncForA();
}

If some method can only be used by in the function void A(), you probably need a class.

But you can do something like this if you want :

#include <iostream>

class ClassTest
{
    public:
        struct A{
            
            private:
               void helperFunc() {
                std::cout << "Executing Helper Func " << std::endl;
                }
            public:   
            void operator() (){
                helperFunc();
            }
        };
    A a;
    
    void classFunc(){
        //a.helperFunc(); <- Impossible helperFunc private
        a(); 
    }
};

int main()
{
    ClassTest c;
    c.classFunc();// Print : Executing Helper Func 
    //OR
    c.a();// Print e: Executing Helper Func 
}

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