【问题标题】:ifstream no matching constructor for initializationifstream 没有匹配的初始化构造函数
【发布时间】:2019-04-24 14:41:17
【问题描述】:

我正在使用 QT Creator 和 MinGW(均为最新版本),但无法让 ifstream 使用在 c++17 中添加的路径参数构造函数。

编译以下代码将失败:

no matching constructor for initialization of 'std::ifstream' 

我的 QT .pro 文件中有 CONFIG += c++17LIBS += -lstdc++fs

MCV https://gcc.godbolt.org/z/Lb3MNT

#include <experimental/filesystem>
#include <fstream>

int main() {
    const std::experimental::filesystem::path my_path = "C:/";
    std::ifstream input_file_stream(my_path);
}

【问题讨论】:

  • 这看起来只是一个声明,它本身不应该导致你提到的错误。请提供一个独立的小例子,可以在cpp.sh 上编译(或产生编译器错误)
  • 如果您改用std::filesystem::path 会发生什么? filesystem 是 C++17 的一部分,因此您不需要 experimental
  • 出现文件系统未找到错误。我假设 MinGW 与 c++17 文件系统不兼容?
  • cpp.sh 找不到头文件系统
  • 有道理,cpp.sh 还不支持 C++17。也许您可以在似乎支持它的gcc.godbolt.orgonlinegdb.com/online_c++_compiler 上执行此操作

标签: c++ qt qt-creator c++17


【解决方案1】:

@ user1406186,我复制了您的相同错误,并且能够将以下更改应用到.pro 文件并必须指定我需要使用的QMAKE 来编译它:

TEMPLATE = app
CONFIG += console c++11

QMAKE_CXXFLAGS += -std=gnu++11
CONFIG -= app_bundle
CONFIG -= qt

SOURCES += \
        main.cpp

HEADERS +=
LIBS += -lstdc++fs

它还使用以下 C++14/C++11 标准编译:

TEMPLATE = app
CONFIG += console c++14

QMAKE_CXXFLAGS += -std=gnu++14
CONFIG -= app_bundle
CONFIG -= qt

SOURCES += \
        main.cpp

HEADERS +=
LIBS += -lstdc++fs

【讨论】:

  • 不幸的是,我仍然遇到同样的错误。一定是编译器?
  • 您使用的是哪个特定的编译器?如果您键入以下指令gcc --version,您的终端上的输出是什么?也尝试在您的终端上运行它并显示输出gcc yourprogram.cpp -o yourprogram
  • 版本 = gcc (MinGW.org GCC-8.2.0-3) 8.2.0
  • 使用 gcc 命令 main.cpp 的编译器输出:在函数“int main()”中:main.cpp:5:12:错误:命名空间“std”中的“文件系统”未命名类型 const std::filesystem::path my_path = "C:/"; ^~~~~~~~~~ main.cpp:6:33: 错误: 'my_path' 未在此范围内声明 std::ifstream input_file_stream(my_path);
  • 您是否在Qt 上设置了编译器? : Tools > Options > C++ , Compilers, Add > MinGW In name put the compiler version, MinGW (version) 这是将在 Kits 中显示的名称 In Compiler path 浏览 C++ 编译器路径,在本例中为 D:\yourPath\ mingw(你的版本)\bin\g++.exe
【解决方案2】:
#include<string>
#include<experimental\filesystem>
using namespace std;
using namespace experimental::filesystem;
int main()
{
    path soure{current_path()};
    soure /="test.txt";

    ifstream input{u8path(soure).u8string()};
    if(!input)
    {
        cout<<"source file not exist"<<endl;
    }
    path dest{current_path()};
    dest /="test-copy.txt";
    ofstream output{u8path(dest).u8string()};

    string line;
    while(!getline(input,line).eof())
    {
        output<<line<<endl;
    }
    input.close();
    output.close();
    return 0;
}

【讨论】:

  • 上述解决方案已使用 Qt creator 进行测试并按预期工作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-17
  • 2017-06-27
  • 1970-01-01
  • 2022-11-17
  • 2018-11-14
相关资源
最近更新 更多