下面的行聲明瞭一個發生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;
}
將你的變量從'cout'重命名爲別的東西。 –
注意''不是標準的C++。標準的C++頭文件沒有'.h'。 ' =>'。 –
NathanOliver
如果程序有'使用命名空間標準;' – drescherjm