string居然也可以用<<和>>
最近在項目工程中碰到一段代碼, 頗為費解, string居然也可以用 <<和>>, 于是我單獨寫了個小程序測了一下:
#include <iostream> #include <string> using namespace std; int main() { int a = 1; string s; s << a; return 0; }
編譯錯誤:error: no match for 'operator<<' in 's << a'
這是正常的。
但為什么在工程項目中就可以呢? 請教了一下別的同事, 才發(fā)現(xiàn), 是對string進行了擴展, 在項目工程中寫測試代碼, 部分代碼如下:
// 工程中的部分代碼 int main() { int a = 1; float b = 2.0f; bool c = true; string d = "hello world"; string s; s << a; s << b; s << c; s << d; cout << "size is " << s.size() << endl; int a2; float b2; bool c2; string d2; s >> a2; s >> b2; s >> c2; s >> d2; cout << a2 << endl; cout << b2 << endl; cout << c2 << endl; cout << d2 << endl; cout << "size is " << s.size() << endl; return 0; }
結果為:
size is 22
1
2
1
hello world
size is 0
可見, string在這里具備了類似流的功能。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。如果你想了解更多相關內容請查看下面相關鏈接
相關文章
C++實現(xiàn)LeetCode(13.羅馬數(shù)字轉化成整數(shù))
這篇文章主要介紹了C++實現(xiàn)LeetCode(13.羅馬數(shù)字轉化成整數(shù)),本篇文章通過簡要的案例,講解了該項技術的了解與使用,以下就是詳細內容,需要的朋友可以參考下2021-07-07