【问题标题】:Passing a value to std::ifstream through constructor通过构造函数将值传递给 std::ifstream
【发布时间】:2014-03-18 19:10:58
【问题描述】:

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

// 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

但是,结果是“调试断言失败!”。

image

编辑: 作为一个相当新手的 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:

【问题讨论】:

  • 不需要指针。使用初始化列表。瞧,不再需要三法则了。
  • 你能显示调用的代码吗?
  • Java 程序员的 C++ 第一课:不要到处使用new
  • “我已经听取了初始化列表的建议,现在这是我的代码” 修改后的代码中没有 ctor-initializer-list。而argc>0 并不意味着argv[1] 可以安全访问。
  • @JonathanWakely 对不起,没有意识到我忽略了你写的第二件事“而且 argc>0 并不意味着 argv[1] 可以安全访问。”,事实证明这毕竟是问题所在.谢谢!

标签: c++ string io ifstream assertion


【解决方案1】:
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,更简单明了。

【讨论】:

    猜你喜欢
    • 2012-08-13
    • 1970-01-01
    • 1970-01-01
    • 2012-03-19
    • 2021-08-27
    • 1970-01-01
    • 1970-01-01
    • 2018-05-09
    • 2015-02-22
    相关资源
    最近更新 更多