通过构造函数向std::ifstream传递一个值

Passing a value to std::ifstream through constructor

本文关键字:一个 构造函数 std ifstream      更新时间:2023-10-16

我正试图通过构造函数传递带有字符串的文件名,我的代码是这样的。为了简单起见,我去掉了一些不必要的东西。

// 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();
}

这没有newdelete,并且更简单、更清晰。

相关文章: