我正在为 nand2tetris 做一个项目。我们在 Jack 中编写一个程序并在 VMEmulator 上对其进行测试。该类如下所示:
class List {
field int data;
field List next;
/* Creates a new List object. */
constructor List new(int car, List cdr) {
let data = car;
let next = cdr;
return this;
}
/* Disposes this List by recursively disposing its tail. */
method void dispose() {
if (~(next = null)) {
do next.dispose();
}
// Use an OS routine to recycle the memory held by this object.
do Memory.deAlloc(this);
return;
}
/* Prints the list*/
method void print() {
do Output.printString(" -> ");
do Output.printInt(data);
if (~(next = null)) {
do next.print();
}
return;
}
/* Inserts the argument in the right position of the list (ascending order)*/
method void insertInOrder(int ins){
var List prev, curr, insert;
let prev = this;
let curr = prev.getnext();
while (ins > prev.getdata()){
if (ins < curr.getdata()){
let insert = List.new(ins, curr);
do prev.setnext(insert);
}
else{
let prev = prev.getnext();
let curr = prev.getnext();
}
}
return;
}
/* Searches the argument in the list, if found, it returns the corresponding List object*/
method List find(int toFind){
var List temp;
var List equal;
var boolean found;
let temp = this;
let found = false;
while (~(next = null)){
if(toFind = temp.getdata()){
let equal = temp;
let found = true;
}
let temp = temp.getnext();
}
if (found){
return equal;
}
else{
return null;
}
}
method List getnext(){
return next;
}
method void setnext(List object){
let next = object;
return;
}
method int getdata(){
return data;
}
}
它有一个私有变量data
和一个指针next
。所以我写了 getter 和 setter 方法来返回这些值。其他方法都很好,只是getdata()
方法不正确。当它通过 VMEmulator 运行时,它会显示错误Out of segment space in List.getdata.3
。这显示在 VMEmulator 中。
0function List.getdata0
1push argument0
2pop pointer0
3push this 0
4return
错误在第 4 行return
。当我更改 Jack 代码时,同样的错误仍然出现在第 4 行。
我的getter方法到底有什么问题?