簡體   English   中英

在 C++ 中封裝輔助函數的正確方法是什么?

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

給定一個類:

class myClass{
// ...

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

// ...
};

假設輔助函數不在A之外A 我如何封裝它們,以便在A之外調用它們是不可能的? 我要不要:

class myClass{
// ...

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

// ...
};

然后通過寫入調用:

myClass obj;
obj.A.call();

? 也許,為了方便起見,我可以重載A()運算符而不是call()函數。 什么是正確的方法?

正確的方法是使用 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();
}

如果某些方法只能在函數 void A() 中使用,則您可能需要一個類。

但是如果你願意,你可以做這樣的事情:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM