繁体   English   中英

通过构造函数将值传递给std :: ifstream

[英]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 == 1argv[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 ,更简单明了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM