一次对类成员的输出试验让我十分困惑,以下是源码:
#include<iostream>
using namespace std;
class m
{
public:
m():num(0){}
int get(){cout<<num<<'c'<<endl;return num;}
int set(int c)
{
num=c;
return num;
}
private:
int num;
};
int main()
{
m M;
cout<<M.set(12)<<'a'<<endl<<M.get()<<'b'<<endl;
return 0;
}
本应输出的结果为
12a
12c
12b
然而运行结果是
抓心挠肺呀,最后经过大牛的帮助下终于明白了cout 栈的原理
cout是从右到左入栈的,过程如下
push endl
push 'b'
call M.get() //打印0c
push eax //push 0
push endl
push 'a'
call M.set(12)
push eax //push 12
push 'b'
call M.get() //打印0c
push eax //push 0
push endl
push 'a'
call M.set(12)
push eax //push 12
也就是遇到函数时执行函数,把返回值压入栈内,最后依次输出