[英]How to initialize an object that declared as const on header file?
I want to initialize std::ifstream object only in the main()
function after declare it in the header.我想在 header 中声明后,仅在
main()
function 中初始化 std::ifstream object。
Is there any way to do it in C++? C++有什么办法吗?
I wrote this but it's not compiling我写了这个但它没有编译
//header.h
#include <iostream>
#include <fstream>
class class1{
static const std::ifstream fs;
};
//proj.cpp
#include "header.h"
void main(){
class1::fs("Employee.txt")
}
static
variables need to be defined at global scope, not inside a function. static
变量需要在全局 scope 中定义,而不是在 function 内部。
main
should also return int
not void
. main
也应该返回int
而不是void
。
A const
std::ifstream
doesn't make much sense as most of the methods you would need to use are non- const
so wouldn't be callable on your const
stream. const
std::ifstream
没有多大意义,因为您需要使用的大多数方法都是非const
,因此无法在您的const
stream 上调用。
Fixing these issues gives:解决这些问题可以得到:
//header.h
#include <iostream>
#include <fstream>
class class1{
static std::ifstream fs;
};
//proj.cpp
std::ifstream class1::fs("Employee.txt");
int main(){
return 0;
}
If you want to open the stream in main
then you need to do:如果你想在
main
中打开 stream 那么你需要做:
const std::ifstream class1::fs;
int main(){
class1::fs.open("Employee.txt");
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.