簡體   English   中英

C ++如何在此程序中執行cout?

[英]C++ How cout is excuted in this program?

首先如何執行tryout.main()cout,然后打印main()函數cout,最后如何打印tryout.main()的返回值。 這有點令人困惑。 有人可以解釋嗎?

#include<iostream>
using namespace std;
class TryOut
{
public:
 int main()
 {
    std::cout<<"In TryOut Main Function "<<std::endl;
    return 0;
 }
};

int main(int argc, char **argv)
{
TryOut tryout;
std::cout<<"In Main function: "<<tryout.main()<<std::endl;
return 0;
}

輸出:

In TryOut Main Function 
In Main function: 0

這是一個編輯過的答案。 伊戈爾·坦德尼克(Igor Tandetnik)證明我做錯了,由於(錯誤地)我的回答被接受並獲得最高投票,因此我決定重寫此文本以使其正確。

就我們而言

foo() = ostream& ostream::operator<<(const char*)

執行順序如下:

obj.foo("str").foo(fun())

可能是:

obj.foo("str");
fun();
obj.foo(fun_res);

要么

fun();
obj.foo("str");
obj.foo(fun_res);

在您的情況下,后者發生了,但是前者也是有效的執行命令。

訂單保證如下:

  • fun()將在obj.foo(fun_res)之前發生,因為該調用需要foo的結果,
  • obj.foo("str")將在obj.foo(fun_res)之前發生。

因此,上述兩種情況都是可能的。

通常,未指定表達式中子表達式的求值順序。 std::cout<<"In Main function: "被執行之前或之后,可以合法地調用tryout.main() 在您的情況下,它恰好在之前被調用。

在C ++中,“ <<”實際上是語法糖

cout << "Hello"

你實際上是在打電話

ostream& operator<<(ostream&, const char*)

要么

ostream&ostream :: operator <<(const char *)

為了方便起見,我將假設后者。 當你寫

std::cout<<"In Main function: "<<tryout.main()<<std::endl;

這將編譯為

cout.operator<<("In Main function: ").operator<<(tryout.main()).operator<<(std::endl);

所以你寫的代碼是

<<tryout.main()<<

表示:“調用tryout.main(),捕獲返回值,然后使用上一個<<返回的ostream將其傳遞給“ ostream :: operator <<(int)”。

所以-現在tryout.main()被調用並執行,它完全獨立地執行自己的輸出,然后返回0。

現在,您的main函數能夠使用返回值0作為參數來完成其調用鏈。

您是否有理由無法使用調試器來完成此步驟?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM