[英]Passing a value to std::ifstream through constructor
我試圖通過構造函數傳遞帶有字符串的文件名,我的代碼是這樣。 為了簡單起見,我刪除了一些不必要的內容。
// header file
Interpreter(const std::string location);
std::ifstream *file;
// end header file
// class file
Interpreter::Interpreter(const std::string location) {
file = new std::ifstream(location.c_str());
}
// end class file
但是,結果是“調試斷言失敗!”。
編輯:作為一個相當新手的C ++程序員(來自Java),我接受了初始化列表的建議,現在這是我的代碼(在標頭中):
std::ifstream file;
Interpreter(const std::string location) {
file.open(location.c_str());
}
但是我仍然遇到同樣的錯誤,有什么幫助嗎? 謝謝!
編輯2:
int main(int argc, char** argv) {
Interpreter *interpreter = nullptr;
// check if arguments are provided
if (argc > 0) {
interpreter = new Interpreter(argv[1]);
} else {
// for now just use the debug script
error("No input files, using default script (debug)");
interpreter = new Interpreter("test.m");
}
interpreter->read();
delete interpreter;
return 0;
}
編輯3
你是說這個初始化列表嗎?
Interpreter::Interpreter(const std::string location): file(location) {
}
編輯4
最后的編輯,謝謝:)原來問題出在參數上
並且argc> 0並不意味着argv [1]是可以安全訪問的。
那是在CPP文件中,並且仍然給出相同的結果。 d:
if (argc > 0) {
interpreter = new Interpreter(argv[1]);
這是不正確的,如果argc == 1
則argv[1]
超出范圍,應該是
if (argc > 1) {
interpreter = new Interpreter(argv[1]);
至於其余的問題,我將這樣編寫構造函數:
Interpreter(const std::string location) : file(location) { }
(在C ++ 11中,您可以從std::string
構造一個fstream
,如果編譯器不起作用,請像以前一樣使用location.c_str()
:
Interpreter(const std::string location) : file(location.c_str()) { }
我會這樣寫你的main
功能:
int main(int argc, char** argv)
{
std::string file;
// check if arguments are provided
if (argc > 1) {
file = argv[1];
} else {
// for now just use the debug script
error("No input files, using default script (debug)");
file = "test.m";
}
Interpreter interpreter(file);
interpreter.read();
}
它沒有new
和delete
,更簡單明了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.