我想在标题中声明Std::IfStream对象之后,只在main()
函数中初始化它。
用C++有什么办法可以做到吗?
我写了这个但是它没有编译
//header.h
#include <iostream>
#include <fstream>
class class1{
static const std::ifstream fs;
};
//proj.cpp
#include "header.h"
void main(){
class1::fs("Employee.txt")
}
statice
变量需要在全局范围内定义,而不是在函数内定义。
main
还应返回int
而不是void
。
const
std::ifstream
没有太大意义,因为您需要使用的大多数方法都是非const
的,因此在const
流上是不可调用的。
修复这些问题可以提供:
//header.h
#include <iostream>
#include <fstream>
class class1{
static std::ifstream fs;
};
//proj.cpp
std::ifstream class1::fs("Employee.txt");
int main(){
return 0;
}
如果要在main
中打开流,则需要执行以下操作:
const std::ifstream class1::fs;
int main(){
class1::fs.open("Employee.txt");
return 0;
}