2017-01-16 88 views
2
#include <conio.h> // include conio.h file 
#include <iostream.h> // or #include<iostream> 

int main() 
{ 
    int cout = 5; 
    cout << cout; 

    return 0; 
} 

爲什麼會發生這種情況?此代碼編譯,但它沒有顯示輸出時它在Visual Studio 2015社區運行(c + +)

的代碼編譯正確,但是當它運行

這不會給輸出5和所有其他的東西

它也不會發出警告它不給預期輸出。

+1

將你的變量從'cout'重命名爲別的東西。 –

+3

注意''不是標準的C++。標準的C++頭文件沒有'.h'。 ' =>'。 – NathanOliver

+0

如果程序有'使用命名空間標準;' – drescherjm

回答

9

下面的行聲明瞭一個發生int被稱爲cout(它不是std::cout流)

int cout = 5; 

<<操作者peforms的比特移位。

所以

cout << cout; 

僅執行比特移位,而不是存儲結果。


要澄清一下,看看下面的程序:

#include<iostream> 

int main() 
{ 
    int cout = 5; 
    auto shiftedval = cout << cout; 
    std::cout << "cout's value is " << cout << ", and the result of the bit shift is " << shiftedval << '\n'; 

    return 0; 
} 

這將輸出:

cout's value is 5, and the result of the bit shift is 160 

什麼幕後發生的事情是,operator<<has been overloaded到在左邊拿一個ostream

通過包括iostream你得到這個功能,編譯器會知道你的意思,如果你有一個ostream<<運營商的左側。

沒有圖書館,<<只是一個bitwise shift operator


還要注意的是,如果你有ill-advisedly包括using namespace std;using std::cout然後cout隨後將意味着ostream<<將觸發圖書館operator<<函數的調用。如果在添加上面的using聲明之後,您包含另一個聲明cout新聲明的名稱will hide先前的聲明和cout現在將再次被視爲int,我們又回到了正在使用的位移運算符功能。

例子:

#include<iostream> 

using namespace std; // using std:: at global scope 

int main() 
{ 
    int cout = 5; 
    auto shiftedval = cout << cout; 

    //the following will not compile, cout is an int: 
    cout << "cout's value is " << cout << ", and the result of the bit shift is " << shiftedval << '\n'; 

    //but we can get the cout from the global scope and the following will compile 
    ::cout << "cout's value is " << cout << ", and the result of the bit shift is " << shiftedval << '\n'; 

    return 0; 
} 
+0

我不明白......請你能解釋一下 –

3

你命名你的變量cout,你與std::cout混淆。您的示例執行bit shift operation。試試這個:

int main() 
{ 
    int cout = 5; 
    std::cout << cout; 

    return 0; 
} 

更重要的是,你命名變量別的避免混淆:

int main() 
{ 
    int foo = 5; 
    std::cout << foo; 

    return 0; 
} 
1

如果不顯式聲明std命名空間,無論是通過在你的代碼using namespace std;或調用std::cout然後cout解析爲您的main()函數中的局部變量cout

即使你聲明using namespace std;cout仍將解析爲本地變量,而不是 - 這就是爲什麼很多人,書籍,教程會建議你明確寫入std::whatever而是採用了命名空間的原因之一。

相關問題