命名空间改变函数定义

juz*_*ode 1 c++ namespaces

我有一小段代码,它只生成一个函数来获取 Windows 或 Linux 平台的当前目录:

#include <stdio.h>  /* defines FILENAME_MAX */
#include <string>
#ifdef WINDOWS
    #include <direct.h>
    #define GetCurrentDir _getcwd
#else
    #include <unistd.h>
    #define GetCurrentDir getcwd
 #endif


    std::string getcwd(){
    char mCurrentPath[FILENAME_MAX];
    GetCurrentDir(mCurrentPath, sizeof(mCurrentPath));
    return *(new std::string (mCurrentPath));

    }
Run Code Online (Sandbox Code Playgroud)

这一切都很棒且有效;但是,我想getcwd()在命名空间中创建函数fUtils,因此我这样做了:

#include <stdio.h>  /* defines FILENAME_MAX */
#include <string>
#ifdef WINDOWS
    #include <direct.h>
    #define GetCurrentDir _getcwd
#else
    #include <unistd.h>
    #define GetCurrentDir getcwd
 #endif

namespace fUtils{
    std::string getcwd(){
    char mCurrentPath[FILENAME_MAX];
    GetCurrentDir(mCurrentPath, sizeof(mCurrentPath));
    return *(new std::string (mCurrentPath));

    }
}
Run Code Online (Sandbox Code Playgroud)

但这给出了一个错误,VSCode其中说:

no matching function for call to 'getcwd'

我在这方面犯了什么错误?如果这不是我将函数放入命名空间的方式fUtils,那么我应该如何将它放入命名空间?

Adr*_*ica 7

您的fUtils::getcwd()函数试图在对宏求值 (to )时调用自身,这会导致函数不期望参数但被赋予两个参数。GetCurrentDirgetcwd

要解决此问题,请::在 的定义中添加全局命名空间运算符 ( ) GetCurrentDir,如下所示:

#ifdef WINDOWS
    #include <direct.h>
    #define GetCurrentDir ::_getcwd
#else
    #include <unistd.h>
    #define GetCurrentDir ::getcwd
#endif
Run Code Online (Sandbox Code Playgroud)

然后,在您的函数体中,编译器很清楚您不是在寻找“递归”(和无效)调用。