[英]Called a function with “cout” statement inside a “cout” statement
在搞亂代碼時我遇到了這種相當模糊的行為,這是一個例子:
#include <iostream>
using namespace std;
int print(void);
int main(void)
{
cout << "The Lucky " << print() << endl; //This line
return 0;
}
int print(void)
{
cout << "No : ";
return 3;
}
在我的代碼中,帶有注釋的聲明//This line
應該打印出The Lucky No : 3
,而是打印出No : The Lucky 3
。 是什么導致這種行為? 這是否與C ++標准有關,或者它的行為因編譯器而異?
未指定對函數的參數的評估順序。 您的行對於編譯器看起來像這樣:
operator<<(operator<<(operator<<(cout, "The Lucky "), print()), endl);
語句中的主要調用是以endl作為參數的調用。 未指定第二個參數endl是首先計算還是更大的子表達式:
operator<<(operator<<(cout, "The Lucky "), print())
並且打破了那個,沒有指定是首先調用函數print()
還是子表達式:
operator<<(cout, "The Lucky ")
那么,回答你的問題:
是什么導致這種行為? 這是否與C ++標准有關,或者它的行為因編譯器而異?
它可能因編譯器而異。
讓我們將operator <<
稱為operator <<
簡單operator
。
現在我們可以寫了
cout << "The Lucky"
如
operator(cout, "The Lucky")
這個操作的結果是cout
,它被傳遞給下一個<<
,所以我們可以寫
operator(operator(cout, "The Lucky"), print() )
它是一個帶有兩個參數的函數調用,標准沒有說明它們的評估順序。
所以對於一些編譯器,你真的可以得到
The Lucky No : 3
在我的編譯器中No:Lucky 3是輸出....這意味着它的行為因編譯器而異。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.