在新对象上使用vector.push_back时,我得到nullReferenceException。
在代码段中,您看到我将矢量对象作为指针,但我最初将它作为非指针,我在绝望中更改了它。
我完全逐步完成了BasicSolver的实例化,以确保其中没有问题,并将实例化与push_back分开,以帮助显示push_back是问题发生的地方。
InformedSolver1& 2是BasicSolver的子级。 vector包含在BasicSolver中,因此也包含在puzzleSolver中。
#include "stdafx.h"
#include "puzzleSolver.h"
PuzzleSolver::PuzzleSolver()
{
solvers = new vector<BasicSolver*>();
}
void PuzzleSolver::createPuzzle(string input)
{ //hitting step-over
BasicSolver* temp = new BasicSolver(input);// no errors
solvers->push_back(temp); // nullReferenceException
solvers->push_back(new InformedSolver1(input));
solvers->push_back(new InformedSolver2(input));
}
这应该是所有相关信息。 如果您对导致此问题/如何解决问题有任何想法,请告诉我们! 感谢。
编辑: 通过评论请求添加了BasicSolver构造函数和依赖项方法 还有一点背景:这是一个AI类的数独求解器
BasicSolver::BasicSolver(string input)
{
peers = new vector<Peer*>();
squares = new vector<Square*>();
unsolved = new vector<Square*>();
solved = new vector<Square*>();
createStructure(input);
original = input;
mistakes = 0;
}
void BasicSolver::createStructure(string input)
{
try
{
createEmptyStructure(peers, squares, unsolved);
//Parse the puzzle and assign input to squares
int numCharsToRead = MAX_SQUARES; //makes sure vector isn't outside its range
if (input.length() < MAX_SQUARES) //makes sure string isn't outside its range
numCharsToRead = input.length();
for (int i = 0; i < numCharsToRead; i++)
{
if(input[i] != '.')
insertValue(input[i], (*squares)[i], unsolved);
}
}
catch(exception e)
{
throw e;
}
}
void BasicSolver::createEmptyStructure(vector<Peer*> *workingPeers, vector<Square*> *workingSquares, vector<Square*> *workingUnsolved)
{
for (int i = 0; i < MAX_PEERS; i++)
{
workingPeers->push_back(new Peer());
}
for (int i = 0; i < 81; i++)
{
try
{
workingSquares->push_back(new Square('.'));
//Adding the square to its corresponding peers
(*workingPeers)[i / MAX_ROWS]->addSquare((*workingSquares)[i]); //adds the square into its appropriate row of peers
(*workingPeers)[(i % MAX_ROWS) + COL_OFFSET]->addSquare((*workingSquares)[i]); //adds the square into its appropriate column of peers
int tempBoxCol = (i % MAX_ROWS) / MAX_BOX_COLS; //returns the box column (0,1,2)
if ((i / MAX_ROWS) < BOX_ROW_WIDTH) //if its box is in the first row
{
(*workingPeers)[tempBoxCol + BOX_OFFSET]->addSquare((*workingSquares)[i]);
}
else if ((i / MAX_ROWS) < (2 * BOX_ROW_WIDTH)) //if its box is in the second row
{
(*workingPeers)[BOX_ROW_WIDTH + tempBoxCol + BOX_OFFSET]->addSquare((*workingSquares)[i]);
}
else //if the box is in the third row
{
(*workingPeers)[2 * BOX_ROW_WIDTH + tempBoxCol + BOX_OFFSET]->addSquare((*workingSquares)[i]);
}
}
catch(exception e)
{
throw e;
}
}
*workingUnsolved = *workingSquares;
}
EDIT2: 个人测试 添加以下行:
vector<BasicSolver*>* test = new vector<BasicSolver*>();
test->push_back(temp);
前
solvers->push_back(temp);
并且它们执行正常,我还注意到在运行时解算器被列为范围之外,即使它是BasicSolver的受保护变量。
答案 0 :(得分:0)
问题是调用源没有正确实例化PuzzleSolver。 感谢@TheDark建议我检查一下!