简体   繁体   中英

C++11 error no match for call to Ifstream outside main

I'm brand new to c++, trying to learn it on my own.

I've found several questions related to this but none of them have really answered it. I've enabled c++11 so ifstream should accept a std::string as far as I can tell. I've also tried this in Visual Studio, CLion, and Eclipse Neon with the exact same results.

I've also checked the value of __cplusplus at runtime and I know it is set to 201103, which is required for the overloading of the constructor.

Essentially if I use std::ifstream in the main function using a std::string I have no problems. On the other hand if I try to pass it to a another class that in another file I receive this error in Eclipse and Clion:

"error: no match for call to '(std::ifstream {aka std::basic_ifstream}) (std::__cxx11::string&)' infile(filename);"

And this error in Visual Studio: "error C2064: term does not evaluate to a function taking 1 arguments"

Both errors point to the same line as indicated in the code block below. I would like to know what I'm doing wrong as I'd like to use ifstream inside of the class.

// 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 doesn't provide a operator()(std::string) overload. Hence

infile(filename);

in the constructor body fails to compile.

There is a constructor taking a const std::string& though, that can be used in your classes member initializer list:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM