// vs 2010
//
#inlcude "stdafx.h"
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
string str;
cout <<str <<endl; // Compilation error.
return 0;
}
當你寫下這樣的代碼時你將會得到一大堆的編譯錯誤, 其中比較有用的在第一行: error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'std::string'.
意思是說, 沒有能夠執行 operator<<(const std::string &) 的函數.
根據我們的常識, 這就像有人突然告訴你世界上再無征稅了一樣, 顯然是有問題的, 那么問題出在了哪里?
記得 Thinking in C++ 一書中說過,
將不是屬於類的行為作為普通或者友員函數實現. 對於本例而言, 對 string 類的輸出不是 string 的行為, 也不是 cout(ostream 的一個對象) 的行為, 因為 cout 不光輸出 string 類型, 它還會輸出別的很多類型. 因此, 對於 string 的輸出, 不應該作為 cout 的一個成員. 所以
cout <<str <<endl;
是無法通過編譯的, 因為 iostream.h 中根本沒有對 operator<<(string) 的重載.
根據 C++ Name lookup 約定, cout 函數會進行如下查找:
- 查找 cout 的命名空間中, 使用點之前是否有 operator<<(std::ostream &, const std::string &) 的聲明.
顯然, iostream 中並沒有相關的函數聲明, 然而真正對於 operator<<(std::ostream &, const std::string &) 的聲明在頭文件 string 中.
將 cout 對 string 的重載放在 string 這個頭文件中是正確的設計. 這也是本文闡述的主旨.
因此, 讓上述代碼工作, 僅需要加入 string 頭文件.