簡體   English   中英

如何初始化在 header 文件中聲明為 const 的 object?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM