Can nonclassical functions be private?

I have some functions in the namespace that I created that are used throughout my program.

In the header file:

namespace NQueens
{
    static int heur = 0;
    int CalcHeuristic(char** state, int size);
    void CalcHorzH(char ** state, int &heuristic, int size);
    void CalcColH(char ** state, int &heuristic, int size);
    void CalcDiagH(char ** state, int &heuristic, int size);
    int calcCollisions(int queensPerRow, int size);
}

Everything works perfectly. However, the only function that is actually called from my external program code is the function CalcHeuristic(char** state, int size). This function then calls other functions.

Since they do not belong to the class, my compiler will not allow me to declare other functions as private. Is there any way to do this? Do I even have to worry about this?

+4
source share
5 answers

Do not declare them in the header, put them in an anonymous namespace in the implementation file.

Example Header:

namespace NQueens
{
    int CalcHeuristic(char** state, int size);
}

Implementation Example:

namespace
{
    static int heur = 0;
    void CalcHorzH(char ** state, int &heuristic, int size);
    void CalcColH(char ** state, int &heuristic, int size);
    void CalcDiagH(char ** state, int &heuristic, int size);
    int calcCollisions(int queensPerRow, int size);
}

namespace NQueens
{
    int CalcHeuristic(char** state, int size)
    {
        // ...
    }
}

namespace
{
    void CalcHorzH(char ** state, int &heuristic, int size) {}
    void CalcColH(char ** state, int &heuristic, int size) {}
    void CalcDiagH(char ** state, int &heuristic, int size) {}
    int calcCollisions(int queensPerRow, int size) { return 0; }
}
+11

, private.
:

:

namespace NQueens {
    static int heur = 0;
    int CalcHeuristic(char** state, int size);
}

.cpp:

namespace {
    void CalcHorzH(char ** state, int &heuristic, int size) {
       // Implementation
    }
    void CalcColH(char ** state, int &heuristic, int size) {
        // Implementation
    }
    void CalcDiagH(char ** state, int &heuristic, int size) {
        // Implementation
    }
    int calcCollisions(int queensPerRow, int size) {
        // Implementation
    }
}

- , static. private, protected public, .

IIRC ( static), ​​ .

protected, .

+5

():

class NQueens
{
public:
  static void CalcHeuristic()
  {
    CalcColH();  // Legal here
  }

private:
  static void CalcColH(){}
}

//...
NQueens::CalcHeuristic(); // Legal
NQueens::CalcColH(); // error

- , . static - .

+4

. cpp .h, .

. . (, , , ) , "" , , , , .

, , , , , .

- .

+1

If functions need to be templates or inline, a typical solution is to put them in a namespace with a name detailand assume that people will not access them.

Otherwise, just do not declare them in the header file.

+1
source

Source: https://habr.com/ru/post/1610298/


All Articles