表达式必须具有 class 类型

The expression must have a class type

我目前正在为我的游戏编写补丁应用程序。因为我习惯用 Java 编程,所以我很难与 C++ 相处,不幸的是,补丁程序必须用 C++ 编写,在 Java 中我可以在 5 分钟内完成,但是一种新语言。 . .没那么多。

这是我当前创建所需文件夹的代码:

#include <windows.h>
#include <stdlib.h>
#include <iostream>

using namespace std;

int main(int argc, char* argv[])
{
    //Set the Strings the Patcher needs.
    string DNGDirectory = "C:\dnGames";
    const char* DDDirectory = "C:\dnGames\DuelistsDance";

    //Create directories if they don't exist yet.
    if (CreateDirectory(DNGDirectory.c_str(), NULL) || ERROR_ALREADY_EXISTS == GetLastError())
    {
        if (CreateDirectory(DDDirectory.c_str(), NULL) || ERROR_ALREADY_EXISTS == GetLastError())
        {
            cout << "Directories successfully created." << std::endl;
        }
    }

    return 0;
}

有一次我使用字符串作为变量,因为这是我从 Google (Create a directory if it doesn't exist) 中挑选的示例代码,但我得到错误 "Das Argument vom Typ ""const char "" ist mit dem Parameter vom Typ ""LPCWSTR"" inkompatibel." (应该是参数“"const char" is incompatible with the parameter of type ""LPCWSTR"” in english)我试图通过使用 "const char*" 作为类型来修复它,但这让我错误 "Der Ausdruck muss einen Klassentyp aufweisen."(它们的表达式必须具有 class 类型)。有人知道如何解决这个问题吗?我为此使用 Visual Studio 2019。

自 C++17(在较小程度上为 14)起,我们可以使用 std::filesystem(C++14 中的 std::experimental::filesystem)来操作文件和创建目录。

例如你的情况:

...
std::filesystem::path DDDirectory("C:\dnGames\DuelistsDance"); 

try {
  std::filesystem::create_directories(DDDirectory); // Creates all the directories needed, like mkdir -p on linux

// Success here

} catch(std::filesystem::filesystem_error& e) {
  // Handle errors here
}

这将使您的错误处理更清晰,并且您的代码可以跨平台(尽管您必须更改路径,但是 std::filesystem::path 在 [=] 上将 / 变成 \ 22=] 无论如何)。它还使您的代码更易于阅读,并且如您所见,更短。

如果有人读到这篇文章并遇到同样的问题,这是最后的解决方法:

  • 更改项目设置以不再使用 unicode
  • 将变量更改为 const char* DNGDirectory = "C:\dnGames";
  • 使用CreateDirectory()并删除变量名后的.c_str()

感谢您的评论和 std::filesystem 的替代解决方案!