簡體   English   中英

為什么這些標頭僅在預編譯的標頭之外起作用?

[英]Why do these headers only work outside of the pre-compiled header?

在stdafx.h中:

#include <fstream>
#include <sstream>

在example.cpp中:

#include <stdafx.h>
std::ifstream in_stream;
std::stringstream st_stream;

如果不將fstream和sstream包括在.cpp文件中,則會出現很多錯誤,例如:

Error   C2079   'in_stream' uses undefined class 
'std::basic_ifstream<char,std::char_traits<char>>'

Error   C2228   left of '.exceptions' must have class/struct/union  

如果將適當的包含項直接放在.cpp文件中,為什么錯誤消失了? 功能不應該完全相同嗎?

應該將其寫為"stdafx.h"而不是<stdafx.h> ,因為"stdafx.h"不是標准的頭文件(這只是C ++道德,不是規則)。

Visual Studio自動創建此文件,並向其中添加一堆頭文件。

如果你有很多的源文件的大型項目,以及<fstream>在許多源文件中使用,則包括<fstream>"stdafx.h" 否則,請避免編輯此文件。

std::ifstream需要<fstream>頭文件。 相關幫助頁面中提到了所需的頭文件。 參見例如std::ifstream help

將相關的頭文件直接添加到"myfile.cpp"文件中:

//myfile.cpp:
#include "stdafx.h"
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
int main(){...}

如果您的項目很小,則可以通過“項目設置”->“ C / C ++”->“預編譯頭”告訴Visual Studio停止使用預編譯頭。 這樣,您可以刪除"stdafx.h"並且源文件將與其他編譯器更加兼容。

暫無
暫無

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

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