通过构造函数向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 == 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
,并且更简单、更清晰。
相关文章:
- 如何使用 swig 修改类构造函数以保留对其中一个构造函数参数的引用?
- 为什么从另一个构造函数内部调用C++构造函数不修改类变量?
- 如何处理没有默认构造函数但在另一个构造函数中构造的对象?
- 我用字符串做了一个C++构造函数,但它不会打印出字符串
- 有一个构造函数,但有两个析构函数
- C++ 如何根据作为输入传递的参数调用一个构造函数或另一个构造函数?
- C 如何仅实现多个继承类的一个构造函数
- 错误:在“(”标记之前进行预期的构造函数、析构函数或类型转换.即使我有一个构造函数
- 让构造函数在其初始化列表中调用同一类的另一个构造函数是否有效
- 创建一个构造函数,即Capabe获取任何数量的参数
- 我如何在类上需要另一个构造函数的对象中声明一个对象
- 使用委托调用构造函数和在另一个构造函数体中调用的区别
- 为什么当我尝试编译时,我的 c++ 代码不断返回对我的一个构造函数的"未定义的引用"?
- C :另一个构造函数的构造函数的隐式调用
- 如何创建一个构造函数,该构造函数吸收char阵列
- 为什么有一个构造函数同时接受initializer_list和一个参数包
- 我有一个构造函数,但我需要将输出返回到 main.cpp.我无法使用获取字符串功能!!任何想法如何实现这一目标?
- 如何在一个构造函数中使用两个可变参数模板参数来绑定两个函数
- 从同一类的另一个构造函数调用构造函数
- 将类的实例传递给另一个构造函数,该构造函数将其对象添加到所传递实例所拥有的列表中