[英]C++: Access violation writing location
使用: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
函數,編譯器就會拋出一個Unhandled異常和Access違規寫入位置。
如果我刪除if
函數並將difficultyLevel
定義為algE只是為了測試同樣的問題。
如果我完全刪除difficultyLevel
並且只是打開文件"algE.txt"
和"algEAnswers"
然后我得到相同的問題但是在代碼點擊while循環時在不同的內存位置。
你的問題在這里:
ElemAlg *ea;
ea->GetQuiz(1);
您沒有創建ElemAlg
的實例,因此您在未初始化的指針上調用成員函數。
因為您調用的成員函數不是虛擬的,所以編譯器不必進行任何運行時查找,這就是調用GetQuiz
。 但是, this
指針將是垃圾(因為ea
未初始化),因此當您訪問成員變量(例如difficultyLevel
)時,您將有未定義的行為。 在您的情況下,未定義的行為會導致訪問沖突。
要么初始化ea
:
ElemAlg *ea=new ElemAlg;
ea->GetQuiz(1)
或者,如果您不需要在堆上分配它,請執行以下操作:
ElemAlg ea;
ea.GetQuiz(1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.