2012-03-11 69 views
9

我的計算機科學教授希望我們找到cout的聲明。我使用g ++和-E參數編譯了一個簡單的Hello World程序。這裏是我的HELLO.CPP是什麼樣子:cout在哪裏申報?

#include <iostream> 

using namespace std; 

int main(){ 

    string name=""; 

    cout << "Good morning! What's your name?"; 

    cin >> name; 

    cout << "Hello " << name << ".\n"; 

    return 0; 

} 

我的編譯命令:

g++ -E hello.cpp > hello.p 

在hello.p,我在VIM跑了搜索,像這樣:

:/cout 

我請參閱以下行:

extern ostream cout; 

那是t他聲明cout,並且coutostream類的一個實例?

編輯:

什麼是wcout聲明那裏?如果我正確地記得字母「w」代表「寬」,但我不知道有什麼含義。什麼是wcoutwostream

+0

我會願意猜測代碼中的某處,當您鏈接到IOStream時,會在您的可執行文件中找到該代碼。 – Kaslai 2012-03-11 04:16:28

+0

@Aslai - 我已經從該代碼中抽出一行。我想知道是否就是這樣。 – Moshe 2012-03-11 04:18:24

+0

試試這個:http://www.cplusplus.com/ - 在搜索框中鍵入'cout'。 – 2012-03-11 04:28:46

回答

8

是的,這確實是std::cout的聲明,發現在<iostream>標頭內。

的相關標準部分可以在§27.4.1 [iostream.objects.overview]找到:

部首<iostream>概要

#include <ios> 
#include <streambuf> 
#include <istream> 
#include <ostream> 

namespace std { 
    extern istream cin; 
    extern ostream cout; 
    extern ostream cerr; 
    extern ostream clog; 
    extern wistream wcin; 
    extern wostream wcout; 
    extern wostream wcerr; 
    extern wostream wclog; 
} 

P1頭<iostream>聲明對象與規定的標準C流相關聯的對象通過<cstdio>(27.9.2)中聲明的函數,並且包含使用這些對象所需的所有頭文件秒。

+0

謝謝。請介意澄清我的編輯? – Moshe 2012-03-11 12:43:24

+0

@Moshe:'wcout'只是'wchar_t'上專用的'basic_ostream',這意味着Windows上的UTF-16和Linux IIRC上的UTF-8。 – Xeo 2012-03-11 16:12:18

2

是cout的聲明,並且cout是ostream類的一個實例嗎?

是的,這是std::cout的聲明,是的這是一個std::ostream的實例。它被聲明爲extern,因此即使該標題包含在多個翻譯單元中,該對象也只被創建一次。

+1

不要忘記'namespace std {...}'部分。它是'std :: ostream std :: cout',而不是':: ostream :: cout'。 – moshbear 2012-03-11 04:21:40