[英]How to initialize an object that declared as const on header file?
我想在 header 中聲明后,僅在main()
function 中初始化 std::ifstream object。
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")
}
static
變量需要在全局 scope 中定義,而不是在 function 內部。
main
也應該返回int
而不是void
。
const
std::ifstream
沒有多大意義,因為您需要使用的大多數方法都是非const
,因此無法在您的const
stream 上調用。
解決這些問題可以得到:
//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
中打開 stream 那么你需要做:
const std::ifstream class1::fs;
int main(){
class1::fs.open("Employee.txt");
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.