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

标签 c++ eclipse c++11 visual-c++ clion

我是 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/

相关文章:

c++ - MPlab 8.83 IDE编译错误

java - 下载好的java包放在哪里?

android - Braintree Android Eclipse ADT中的Gradle入门

java - 如何将 Button 对齐到 LinearLayout 中的最右角?

c++ - 这被认为是有效的 c++11 或 c++14 吗?还是 gcc/clang 弄错了?

c++ - C++ 标准是否要求有符号整数只有一个符号位?

c++ - 驱动函数到底是什么?

c++ - 结构原型(prototype)?

c++ - 将内存分配给类的指针

c++ - 等效于嵌套 for 循环的迭代器显示 50% 的性能故障 - 为什么?