//Listing 9.cpp OverLoading operator<<()
#include<iostream>
#include<string.h>
using namespace std;
class String{
public:
String();
String(const char * const);
String(const String &);
~String();
char & operator[](int offset);
char operator[](int offset) const;
String operator+(const String&);
void operator+=(const String &);
String & operator=(const String &);
friend ostream & operator<<(
ostream& theStream,String& theString);
int GetLen() const { return itsLen; }
const char * GetString() const { return itsString; }
private:
String(int);
char * itsString;
unsigned short itsLen;
};
String::String(){
itsString = new char[1];
itsString[0] = '"0';
itsLen = 0;
}
String::String(int len){
itsString = new char[len+1];
for(int i = 0; i<= len; i++)
itsString[i] = '"0';
itsLen = len;
}
String::String(const char * const cString){
itsLen = strlen(cString);
itsString = new char[itsLen+1];
for(int i = 0;i<itsLen; i++)
itsString[i] = cString[i];
itsString[itsLen] = '"0';
}
String::String(const String & rhs){
itsLen = rhs.GetLen();
itsString = new char[itsLen+1];
for(int i= 0;i<itsLen;i++)
itsString[i] = rhs[i];
itsString[itsLen] = '"0';
}
String::~String(){
delete [] itsString;
itsLen = 0;
}
String & String::operator=(const String & rhs){
if(this == &rhs)
return * this;
delete[] itsString;
itsLen = rhs.GetLen();
itsString = new char[itsLen+1];
for(int i= 0;i<itsLen;i++)
itsString[i]=rhs[i];
itsString[itsLen] = '"0';
return *this;
}
char & String::operator[](int offset){
if(offset >itsLen)
return itsString[itsLen+1];
else
return itsString[offset];
}
char String::operator[](int offset) const{
if(offset >itsLen)
return itsString[itsLen-1];
else
return itsString[offset];
}
String String::operator+(const String& rhs){
int totalLen = itsLen + rhs.GetLen();
String temp(totalLen);
int i,j;
for(i = 0;i<itsLen;i++)
temp[i] = itsString[i];
for(j = 0;j<rhs.GetLen();j++,i++)
temp[i] = rhs[i];
temp[totalLen] = '"0';
return temp;
}
void String::operator+=(const String& rhs){
unsigned short rhsLen = rhs.GetLen();
unsigned short totalLen = itsLen + rhsLen;
String temp(totalLen);
int i,j;
for(i = 0;i<itsLen;i++)
temp[i] = itsString[i];
for(j = 0;j<rhs.GetLen();j++,i++)
temp[i] = rhs[j];
temp[totalLen] = '"0';
*this = temp;
}
ostream & operator<< ( ostream & theStream,String & theString){
theStream << theString.itsString;
return theStream;
}
int main(){
String theString("Hello world.");
cout << theString << endl;
return 0;
}
这个程序中使用了友元声明一个 friend ostream& operator<<(ostream& theStream,String& theString);
我开始不明白它为什么要返回一个引用,后来看了后来的章节才知道是怎么回事。
ios类是输入输出流的基类。istream和ostream从 ios类中派生而来,分别用于输入和输出行为。iostream是从istream和 ostream 中派生而来。
那么operator<<为什么要返回一个ostream对像的引用呢?请看例子
cout << itString << "aaaaaa";
我们知道 cout 是一个全局对像是用来输出的,但在上面的例子中如果cout 调用完了之后不返回一个用于输出的引用,那么后面的"aaaaa"说无法输出了,
所以必须返回一个相同的引用用来对下一个进行输出。
同理重载>>运算符时一定要记行返回一个 istream的引用。
小小心得,希望能对你有所帮助。
转载于:https://www.cnblogs.com/unipower/archive/2009/03/03/1402404.html