to: mahatma_cn(鱼和胸罩不可兼得) 这个全局函数怎么由别人去用呀,弄点伪代码来瞧瞧to:sgnaw(李逍遥) 怎么说到关键的地方就不说了?按我的理解来说,<<都应该由要输出的类来重载,并且要做为全局函数来重载,可是我就奇了怪了,没见到string有重载<<的代码
由string来重载.msdn的描述. Illustrates how to use the string::operator<< Standard Template Library (STL) function in Visual C++.template<class _E, class _TYPE, class _A> inline basic_ostream<_E, _TYPE>&operator<<( basic_ostream<_E, _TYPE>& OStream, const basic_string<_E, _TYPE, _A>& XString);Note The class/parameter names in the prototype do not match the version in the header file. Some have been modified to improve readability. Res The operator<< is used to insert a string into an output stream. Example // StringInsertion.cpp // compile with: /EHsc // Illustrates how to use the insertion operator // (operator<<) to insert a string into an output // stream. // // Functions: // // operator<< Inserts a string into an output stream. //////////////////////////////////////////////////////////////////////#pragma warning(disable:4786) #include <string> #include <iostream>using namespace std ;int main() { string msg="Hello! This is the insertion operator."; cout << msg << endl; } Output Hello! This is the insertion operator.
Not the string !!
怎么说到关键的地方就不说了?按我的理解来说,<<都应该由要输出的类来重载,并且要做为全局函数来重载,可是我就奇了怪了,没见到string有重载<<的代码
Illustrates how to use the string::operator<< Standard Template Library (STL) function in Visual C++.template<class _E, class _TYPE, class _A> inline
basic_ostream<_E, _TYPE>&operator<<( basic_ostream<_E, _TYPE>& OStream,
const basic_string<_E, _TYPE, _A>& XString);Note The class/parameter names in the prototype do not match the version in the header file. Some have been modified to improve readability.
Res
The operator<< is used to insert a string into an output stream.
Example
// StringInsertion.cpp
// compile with: /EHsc
// Illustrates how to use the insertion operator
// (operator<<) to insert a string into an output
// stream.
//
// Functions:
//
// operator<< Inserts a string into an output stream.
//////////////////////////////////////////////////////////////////////#pragma warning(disable:4786)
#include <string>
#include <iostream>using namespace std ;int main()
{
string msg="Hello! This is the insertion operator.";
cout << msg << endl;
}
Output
Hello! This is the insertion operator.
ostream& operator<<(ostream cout,string &str)
{
for(int i=0;i<str.lenght()+1;i++)
cout<<str[i]; //operator[]也重载过
return cout;
}