程序中的抽象类 我应该编写C++程序,它被塑造成

程序中的抽象类 我应该编写C++程序,它被塑造成,c++,C++,,正如杰斯特指出的,这是一个愚蠢的任务,但是如果你能很好地理解栈,你应该能够解决它。 您当前的代码: ; For example let's say sp = 54 (address 54 in memory) push ax ; store argument n, sp = 52 call suma ; do the call ; inside suma under the argument there are pushed also ; return address b

,正如杰斯特指出的,这是一个愚蠢的任务,但是如果你能很好地理解栈,你应该能够解决它。 您当前的代码:

; For example let's say sp = 54  (address 54 in memory)
push ax    ; store argument n, sp = 52
call suma  ; do the call
   ; inside suma under the argument there are pushed also
   ; return address by CALL, sp =50
   ; and old bp by PUSH bp, sp = 48
   ; then [sp+4] points to argument n (48+4 = 52)
; stack is restored by the function ("ret 2"), sp = 54
现在,如果要将结果放在堆栈上,则必须从调用方的角度保留堆栈空间,因为在
suma
返回后,
sp
在我的示例中恢复为“54”,并且从
suma
调用较低的
sp
地址写入堆栈的任何内容都可能已经被覆盖(例如,如果中断发生在
ret 2
和下一条指令之间,那么中断确实使用了地址54下面的堆栈内存,并将其覆盖)。而写入地址54+内存中的任何内容都将对调用方有效,但会破坏调用方存储在那里的值

顺便说一句,您当前的代码不会在
ax
中返回结果,因为它以错误的方式执行递归时会覆盖它本身,并且会在地址
sum
处的内存中累积结果,该地址不是由
suma
初始化的,因此它只能工作一次。可以这样编写,递归将返回co即使对于多个调用,也要更正总和(首先将总和归零,然后调用F(n-1)并根据需要在该F(n-1)的结果中添加“n”)


因此,要么决定返回值来代替参数n,然后必须:

  • 内部
    suma
    将结果存储到
    [ebp+4]
    内存中
  • 通过
    ret
    返回(不从堆栈中释放参数)
  • 调用suma
    everywhere
    pop ax
    后,从堆栈中选择结果

或在参数上方保留堆栈空间,如:

sub  sp,2 ; make space for result in stack
   ; you can also use another bogus "push ax", not caring about value, just adjusting sp
push ax   ; push argument n
call suma
pop  ax   ; read result + restore stack
然后在
suma
中,您必须将结果存储到
[bp+6]
ret2
保持原样,只释放参数



无论哪种方式,堆栈空间都必须由调用方保留,因为任何未保留的堆栈空间(低于当前值
sp
)都可能随时被中断处理程序覆盖(在x86 16b实模式下)。

如果不通过堆栈返回值,则在寄存器中返回它们(通常
ax
).PS:注释你的代码,特别是如果你希望别人帮助的话。那句话中的“你”指的是“一般做法”。人们不会在堆栈上返回值(除了浮点或不同的体系结构)。所以不要尝试这样做。