gpt4 book ai didi

C++11 错误不匹配调用 main 之外的 Ifstream

转载 作者:行者123 更新时间:2023-11-28 05:25:22 27 4
gpt4 key购买 nike

我是 c++ 的新手,正在尝试自学。

我发现了几个与此相关的问题,但没有一个真正回答过。我已经启用了 c++11,所以 ifstream 应该接受一个 std::string 据我所知。我还在 Visual Studio、CLion 和 Eclipse Neon 中进行了尝试,结果完全相同。

我还在运行时检查了 __cplusplus 的值,我知道它设置为 201103,这是重载构造函数所必需的。

基本上,如果我在使用 std::string 的主函数中使用 std::ifstream,我没有任何问题。另一方面,如果我尝试将它传递给另一个文件中的另一个类,我会在 Eclipse 和 Clion 中收到此错误:

“错误:不匹配调用'(std::ifstream {aka std::basic_ifstream}) (std::__cxx11::string&)' infile(filename);”

Visual Studio 中的这个错误:“错误 C2064:术语未计算为采用 1 个参数的函数”

两个错误都指向同一行,如下面的代码块所示。我想知道我做错了什么,因为我想在类里面使用 ifstream。

// main.cpp
#include test.h
int main() {
std::string name("test.txt");
TestClass test (name);
std::ifstream testfile(name);
return 0;
}

// test.h
#include <fstream>
class TestClass{
std::ifstream infile;
public:
TestClass(std::string filename); // have also tried with std::string& filename
}

// test.cpp
TestClass::TestClass(std::string filename){ // again have tried using string&
infile(filename); /** ERROR **/
}

最佳答案

std::ifstream 不提供 operator()(std::string) 重载。因此

infile(filename);

在构造函数体中编译失败。

虽然有一个构造函数采用 const std::string&,但它可以在您的类成员初始化列表中使用:

TestClass::TestClass(std::string filename) : infile(filename) {
// Omit that completely: infile(filename); /** ERROR **/
}

关于C++11 错误不匹配调用 main 之外的 Ifstream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40666654/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com