2010-07-14 47 views
1

工作在下面的代碼:重載運算符<<以字符串

using namespace std; 

//ostream& operator<< (ostream& out,const string & str) 
//{  
// out << str.c_str();  
// return out; 
//} 

int _tmain(int argc, _TCHAR* argv[]) 
{ 

    ofstream file("file.out"); 

    vector<string> test(2); 

    test[0] = "str1"; 
    test[1] = "str2"; 
    ostream_iterator<string> sIt(file); 

    copy(test.begin(), test.end(), sIt); 

    file.close(); 
    return 0; 
} 

什麼是重載operator <<,使 copy(test.begin(), test.end(), sIt);工作的正確方法。

我錯過了什麼?

編輯:我只是愚蠢......忘了,包括「弦」頭

謝謝!

+0

要格式化代碼,使用1010按鈕。 – 2010-07-14 10:16:26

回答

6

你不需要重載operator<<來處理字符串,它已經知道如何處理它們。

std::copy(test.begin(), test.end(), 
      std::ostream_iterator<std::string>(file, "\n")); 

會產生:

str1 
str2 

有什麼不同/特別要在那裏做什麼?

+1

這個 - 在中已經有一個運算符<< overload。 – Puppy 2010-07-14 10:23:56

+0

我很笨!之所以上述不工作實際上是有趣的:)(提示:缺少包括)p.s.對不起,這個愚蠢的問題:) – HotHead 2010-07-14 10:29:46

2

正如David已經指出的那樣,字符串已經有一個operator<<,所以你不必提供一個字符串。如果你真的想要定義自己的過載,那麼就有一個小問題,因爲實際上你不允許這樣做。 operator<<定義在std命名空間中,所以如果你想有一個可用的重載std::string(大多數實現中的版本是模板函數,所以有潛在的過載),你必須在std命名空間(這是因爲在C++中解決歧義和重載的方式,這裏有一些注意事項)。例如:

namespace std { 
ostream& operator<< (ostream& out,const string & str) 
    {  
    out << "A STRINGY:" << str.c_str();  
    return out; 
    } 
} 

然而,添加的東西到std命名空間不允許普通用戶,因爲它可能是不可預見的,並可能打破各種東西的標準庫中實施的具體效果。此外,不能保證您的標準庫的實施具有可重載的運營商< <。這意味着,它可以工作或不能。