【发布时间】:2013-03-21 21:15:25
【问题描述】:
我的代码中有一个名为“schemeList”的对象,如下所示:
class scheme;
class schemeList
{
friend class scheme;
private:
scheme * head;
schemeList * tail;
public:
schemeList();
Token addScheme(vector <Token> &toAdd);
//...other functions
};
我遇到问题的函数是“addScheme”,它应该向头部添加一个方案,或者如果头部已满,则将其添加到尾部(以链表的方式)。这是我到目前为止的功能:
Token schemeList::addScheme(vector<Token>& toAdd)
{
if (head->retCloseParen() != ')')
{
scheme * headCopy = head;
Token answer = head->addScheme(toAdd);
head = headCopy;
return answer;
}
else
{
//deal with tail
schemeList * arrow = this;
while (arrow->tail != NULL)
{
arrow = arrow->tail;
}
tail = new schemeList();
tail->head= new scheme();
tail->tail = NULL;
Token answer = arrow->tail->addScheme(toAdd);
return answer;
}
}
这适用于添加第一个方案,但第二个方案会引发错误,显示“未处理的异常...”。我之前遇到过这样的问题,但我通过引用传递变量 toAdd 而不是传递整个对象来修复它。为什么这会引发错误和/或我该如何解决?
为了让事情更清楚,一个方案是:
class scheme
{
friend class identifierList;
public:
Token * id;
char openParen;
char closeParen;
identifierList * idList;
scheme();
//other functions
};
class identifierList
{
friend class scheme;
public:
Token * id;
identifierList * next;
identifierList(Token * inId, identifierList * inNext);
};
一个令牌是:
class Token
{
friend class datalogProgram;
public:
int lineNumber;
string type;
string value;
Token(string inType, string inValue, int inLineNum);
//other functions
};
【问题讨论】:
-
你应该使用
std::list或std::vector而不是浪费时间重新发明链表。 -
显示您的
scheme::addScheme实现。以及获得异常的调用堆栈。
标签: c++ memory-management stack pass-by-reference datalog