【发布时间】:2014-10-20 14:45:28
【问题描述】:
使用:MSVS2012
代码
elemalg.h
#include <vector>
#include <string>
#include <fstream>
class ElemAlg
{
private:
std::string difficultlyLevel, question, answerToRead;
std::vector<std::string> questions, answers;
std::vector<std::string> GetQuiz(int);
};
elemalg.cpp
#include "elemalg.h"
std::vector<std::string> ElemAlg::GetQuiz(int difficulty)
{
if (difficulty == 1) { difficultyLevel = "algE"; }
if (difficulty == 2) { difficultyLevel = "algM"; }
if (difficulty == 3) { difficultyLevel = "algH"; }
if (difficulty == 4) { difficultyLevel = "algVH"; }
std::ifstream fin(difficultyLevel + ".txt");
while (std::getline(fin, question)) { questions.push_back(question); }
fin.close();
std::ifstream fin2(difficultyLevel + "Answers.txt");
while (std::getline(fin2, answerToRead)) { answers.push_back(answerToRead); }
fin2.close();
return questions;
}
MathTutor.cpp
#includes etc
ElemAlg *ea;
ea->GetQuiz(1);
GetQuiz肯定是传入了一个1到4之间的整数,这个是在方法调用之前验证的
difficultyLevel是头文件中定义的字符串。
编译器在遇到第一个if 函数时立即抛出未处理的异常和访问冲突写入位置。
如果我删除 if 函数并将 difficultyLevel 定义为 algE 只是为了测试相同的问题。
如果我完全删除 difficultyLevel 并以 "algE.txt" 和 "algEAnswers" 的身份打开文件,那么一旦代码遇到 while 循环,我就会遇到同样的问题,但在不同的内存位置。
【问题讨论】:
-
difficultyLevel到底是什么? -
参数应该在函数内部使用断言而不是外部进行验证。如果 questions 是一个全局变量,我不知道你为什么要尝试返回它。
-
MCVE 或者它没有发生。
-
您的 ElemAlg 对象无效。我认为您需要将周围的代码发送给我们。
-
@user3001499 -
If I remove the if functions and define difficultyLevel as algE just for testing the same problem你应该停止删除代码,而是保留原来的错误代码,了解它为什么会给你带来问题并修复它。删除代码可能会隐藏错误,给你一种错误的感觉,即你已经“通过魔法”解决了问题。
标签: c++ access-violation unhandled-exception