簡體   English   中英

C ++ 11錯誤,無法在主外部調用Ifstream

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM