Опитвам се да предам име на файл с низ през конструктор, кодът ми е този. Извадих някои от ненужните неща за простота.
// 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:
Отговори:
1 за отговор № 1if (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 можете да създадете fstream
от std::string
, ако това не работи с вашия компилатор тогава използвайте 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
и е по-прост и ясен.