關於C++中cout的使用,相信大家再熟悉不過了,然而對於cout是如何輸出的?輸出的機制是啥,需要進一步的瞭解。本章娓娓道來。前幾天在網上看到這麼一個題目:
View Code
#include <iostream>
using namespace std;
int hello1();
int hello2();
int main()
{
int a, b;
cout<<"a="<<hello1()<<" b="<<hello2()<<endl;
return 0;
}
int hello1()
{
cout<<"hello1"<<endl;
return 1;
}
int hello2()
{
cout<<"hello2"<<endl;
return 2;
}
最終輸出是:
hello2
hello1
a=1 b=2
一時讓人有點難以琢磨,網上給出了其靠譜的解釋:cout流的操作順序是:先從右往左讀入緩衝區,然後再從左往右輸出。所以它從右邊往左讀的時候,碰到了函數當然去執行函數先了,然後把函數傳回值讀入緩衝區再然後。。。就是從左輸出了。
根據這個解釋,有實驗的幾個程式,能加深點理解
程式1:
View Code
#include <iostream>
using namespace std;
int main()
{
int b[2]={1,2};
int *a=b;
cout<<*a<<" "<<*(a++)<<endl;
return 0;
}
輸為出:2 1。
解釋:先讀入*(a++),對於a++,是先讀入緩衝區,其自增,所以,此時緩衝區中的a是1,。再讀入*a,此時a已自增,所以讀入緩衝區的是2.
程式2:
View Code
#include <iostream>
using namespace std;
int main()
{
int i=5;
cout<<i<<" "<<(i++)<<" "<<(++i)<<endl;
return 0;
}
輸出為:7 6 6
解釋:從右往左,先是(++i),即先自增,再讀入緩衝區,為6。再是(i++),即先讀入緩衝區,為6,再自增。最後是i,讀入緩衝區為7.