1、代码如下:
注意:形参加上const修饰符,函数体里面判断参数是否为NULL,引用不能为空等。
复制操作符应该判断是否是自赋值。
重载输入操作符时,要注意给data分配足够的空间,现在还没有想到太好的办法,用的是临时变量,这里一直不是很明白C++中的(string s; cin>>s;)到底最大可以读取多少个字符,其原理又是怎么实现的呢。
友元函数有时候编译器会有bug,解决方法如下:事先声明类和友元函数(在类外面不能用friend 关键字)
class String;
ostream& operator<<(ostream& out,const String& s);
stream& operator>>(istream& in,const String& s);
bool operator<(const String& s1,const String &s2);
- <pre class="html" name="code">#include "stdafx.h"
- #include <iostream.h>
- #include <string.h>
- class String
- {
- public:
- String();
- String(const char *str);
- String(const String &s);
- ~String();
- String& operator=(const String &str);
- friend ostream& operator<<(ostream& out,const String& s);
- friend istream& operator>>(istream& in,String& s);
- friend bool operator<(const String& s1,const String &s2);
- char& operator[](int pos)
- {
- cout<<"index operator"<<endl;
- int len=strlen(data);
- if (pos>=len)
- {
- return data[len-1];
- }
- else
- {
- return data[pos];
- }
- }
- private:
- char *data;
- };
- //默认构造函数
- String::String()
- {
- cout<<"default constructor"<<endl;
- data=new char[1];
- *data='\0';
- }
- //带参数构造函数
- String::String(const char *str)
- {
- cout<<"parameter constructor"<<endl;
- if (str==NULL)
- {
- data=new char[1];
- *data='\0';
- }
- else
- {
- int len=strlen(str);
- data=new char[len+1];
- strcpy(data,str);
- }
- }
- //复制构造函数
- String::String(const String &str)
- {
- cout<<"copy constructor"<<endl;
- int len=strlen(str.data);
- data=new char[len+1];
- strcpy(data,str.data);
- }
- //析构函数
- String::~String()
- {
- cout<<"destructor"<<endl;
- delete[] data;
- }
- //赋值操作符
- String& String::operator=(const String &str)
- {
- cout<<"assign operator"<<endl;
- if (this!=&str)
- {
- int len=strlen(str.data);
- delete[] data;
- data=new char[len+1];
- strcpy(data,str.data);
- }
- return *this;
- }
- //输出操作符
- ostream& operator<<(ostream& out,const String& s)
- {
- cout<<"cout operator"<<endl;
- out<<s.data<<endl;
- return out;
- }
- //输入操作符
- istream& operator>>(istream& in,String& s)
- {
- cout<<"cin operator"<<endl;
- //这个地方很伤神,目前没有想到很好的办法,只能先用中间变量来获取输入的长度,然后释放中间变量
- char *sTemp=new char[1000];
- in>>sTemp;
- delete[] s.data;
- int len=strlen(sTemp);
- s.data=new char[len+1];
- strcpy(s.data,sTemp);
- delete[] sTemp;
- return in;
- }
- //比较操作符
- bool operator<(const String& s1,const String &s2)
- {
- cout<<"compare operator"<<endl;
- if (strcmp(s1.data,s2.data)<0)
- {
- return 1;
- }
- return 0;
- }
- void main()
- {
- String s1; //default constructor
- String s2("12345"); //parameter constructor
- String s3=s2; //copy constructor
- s1=s2; //assign operator
- cin>>s1; //输入操作符
- cout<<s1; //输出操作符
- cout<<(s1<s2)<<endl; //比较操作符
- cout<<(s1[5])<<endl; //获取字符
- //destructor destructor destructor
- }</pre>
- <pre></pre>
- <p> </p>
- <pre></pre>