为什么这些标头仅在预编译的标题外工作
Why do these headers only work outside of the pre-compiled header?
in stdafx.h:
#include <fstream>
#include <sstream>
示例.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>
在许多源文件中使用,则在"stdafx.h"
中包括<fstream>
。否则避免编辑此文件。
std::ifstream
需要<fstream>
标头文件。相关帮助页面中提到了所需的标头文件。例如,请参见std::ifstream help
直接在"myfile.cpp"
文件中添加相关的标头文件:
//myfile.cpp:
#include "stdafx.h"
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
int main(){...}
如果您有一个小型项目,则可以告诉Visual Studio通过"项目设置" ->" C/C " ->"预编译标头"停止使用预编译标头。这样,您可以删除"stdafx.h"
,并且源文件将与不同的编译器更兼容。