【发布时间】: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
但是,结果是“调试断言失败!”。
编辑: 作为一个相当新手的 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