fstream 对象无法被 Visual Studio 的 JIT/Compiler 识别

fstream object not recognized by Visual Studio's JIT/Compiler

本文关键字:JIT Compiler 识别 Studio Visual 对象 fstream      更新时间:2023-10-16

我目前有两个文件,globals.hmainmenu.cpp,它们是旨在模拟书店的更大控制台应用程序的一部分。

可以在下面找到相关的代码位。

<小时 />

全局.h

using std::fstream;
#ifndef GLOBALS_H
#define GLOBALS_H
// Other global variables here
extern fstream datafile;
#endif
<小时 />

主菜单.cpp

#include <fstream>
#include <ios>
#include "globals.h"
using namespace std;
fstream datafile;
datafile.open("inventory.txt", ios::in | ios::out);
<小时 />

由于我目前不明白的原因,Visual Studio 在datafile.open()行告诉我datafile"没有存储类或类型说明符",当我尝试编译时,我得到以下输出:

1>------ Build started: Project: SerendipityBooksellers, Configuration: Debug Win32 ------
1>  mainmenu.cpp
1>c:pathtoprojectmainmenu.cpp(32): error C2143: syntax error : missing ';' before '.'
1>c:pathtoprojectmainmenu.cpp(32): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:pathtoprojectmainmenu.cpp(32): error C2371: 'datafile' : redefinition; different basic types
1>          c:pathtoprojectglobals.h(19) : see declaration of 'datafile'
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

我一直在搜索Google和StackOverflow,但似乎找不到任何我想要的解决方案 - 我做错了什么?我唯一能想到的是,它抱怨我正在使用通用fstream对象代替ifstreamostream对象。

C++不支持

文件级别的代码。它需要进入一个函数。例如,您可以拥有:

fstream datafile;
void open_datafile()
{
    datafile.open("inventory.txt", ios::in | ios::out);
}

显然,您需要从其他地方调用该函数。

此外,C++确实在文件级别提供任意构造函数执行权限。如果您只想在程序启动后立即初始化文件,则可以使用 fstream 构造函数,该构造函数接受与 open 相同的参数:

fstream datafile("inventory.txt", ios::in | ios::out);

请记住,全局变量的构造顺序在很大程度上是未指定的。全局变量在单个 C++ 文件中按其声明顺序进行初始化,但未指定文件之间的顺序。应避免从此类表达式使用非平凡构造函数引用另一个全局变量。