2016-06-21 35 views
1

我不知道我的代碼有什麼問題。我試圖從控制檯獲取兩個文件的文件路徑,然後使用這些文件初始化一些fstream對象,爲另一個添加ios::binaryC++:試圖通過fstream作爲參數時刪除函數?

這裏是我的代碼的重要部分:

// Function prototypes 
void INPUT_DATA(fstream); 
void INPUT_TARGETS(fstream); 

int main() 
{ 
    // Ask the user to specify file paths 
    string dataFilePath; 
    string targetsFilePath; 
    cout << "Please enter the file paths for the storage files:" << endl 
     << "Data File: "; 
    getline(cin, dataFilePath); // Uses getline() to allow file paths with spaces 
    cout << "Targets File: "; 
    getline(cin, targetsFilePath); 

    // Open the data file 
    fstream dataFile; 
    dataFile.open(dataFilePath, ios::in | ios::out | ios::binary); 

    // Open the targets file 
    fstream targetsFile; 
    targetsFile.open(targetsFilePath, ios::in | ios::out); 

    // Input division data into a binary file, passing the proper fstream object   
    INPUT_DATA(dataFile); 

    // Input search targets into a text file 
    INPUT_TARGETS(targetsFile); 

    ... 
} 

// Reads division names, quarters, and corresponding sales data, and writes them to a binary file 
void INPUT_DATA(fstream dataFile) 
{ 
    cout << "Enter division name: "; 
    ... 
    dataFile << divisionName << endl; 
    ... 
} 

// Reads division names and quarters to search for, and writes them to a file 
void INPUT_TARGETS(fstream targetsFile) 
{ 
    cout << "\nPlease input the search targets (or \"exit\"):"; 
    ... 
    targetsFile.write(...); 
    ... 
} 

但是,Visual Studio的罵我的INPUT_DATA(dataFile);INPUT_TARGETS(targetsFile);部分,他說:

function "std::basic_fstream<_Elem, _Traits>::basic_fstream(const std::basic_fstream<_Elem, _Traits>::_Myt &) [with _Elem=char, _Traits=std::char_traits<char>]" (declared at line 1244 of "c:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\fstream") cannot be referenced -- it is a deleted function 

我在頭文件周圍挖直到我找到1244行:

basic_fstream(const _Myt&) = delete; 

我不知道wh這發生了。我對C++還很陌生,我可能只是做了一些愚蠢的事情,但是有人能幫忙嗎?

編輯:澄清標題

回答

3

您不能複製一個std::fstream,所以拷貝構造函數被刪除,因爲你發現了通過挖掘身邊:)

也沒有理由複製std::fstream。在你的情況下,你想通過引用來傳遞它,因爲你想修改原來的std::fstream,你在main中創建的那個,而不是創建一個全新的(這就是爲什麼拷貝構造函數被刪除,btw :))。

+2

最重要的是,改變函數以使用'std :: istream&'允許它們處理的不僅僅是文件。例如,能夠通過傳入字符串流來測試其邏輯。 – chris

2

這是因爲std::fstream的拷貝構造函數被刪除。你無法通過價值來傳遞它。 爲了解決這個問題,通過引用傳遞std::fstream的,就像這樣:

void INPUT_DATA(fstream& dataFile) { /* ... */ } 
void INPUT_TARGETS(fstream& targetsFile) { /* ... */ } 

你不必改變任何代碼中的其他人。