我在我创建的命名空间中有一些函数在我的程序中使用.
在头文件中:
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);
}
Run Code Online (Sandbox Code Playgroud)
一切正常.但是,从我的外部程序代码实际调用的唯一函数是CalcHeuristic(char** state, int size)函数.然后该函数调用其他函数本身.
由于这些不属于某个类,我的编译器不会让我声明其他函数private.有没有办法做到这一点?我应该担心吗?
mol*_*ilo 11
不要在头文件中声明它们,将它们放在实现文件中的匿名命名空间中.
示例标题:
namespace NQueens
{
int CalcHeuristic(char** state, int size);
}
Run Code Online (Sandbox Code Playgroud)
示例实现:
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; }
}
Run Code Online (Sandbox Code Playgroud)
不,你不能做自由职业private.
你可以做的不是在命名空间中声明它们并在翻译单元中使用匿名命名空间:
在标题中:
namespace NQueens {
static int heur = 0;
int CalcHeuristic(char** state, int size);
}
Run Code Online (Sandbox Code Playgroud)
在.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
}
}
Run Code Online (Sandbox Code Playgroud)
另一种选择是使用类而不是命名空间,包含所有这些函数作为static函数成员.您可以使用所有常用的范围语义的private,protected和public再.
但是IIRC这样的类(仅包含static函数成员)并不被认为是良好的做法,而不是将函数置于名称空间中.
虽然如果你想实现一种protected继承,那么这种方法可能会被认为是有用的.