运算符重载
#include <iostream>
using namespace std;
class MyString{
char*_ptr;
int _size;
public:
MyString(int=10);
MyString(char*str);
MyString(const MyString&obj);
~MyString(){delete[]_ptr;}
char& operator[](int i);
int size()const;
MyString& operator=(const MyString& str);
MyString& operator+(const MyString& str);
bool operator == (const MyString& str);
bool operator < (const MyString& str);
bool operator > (const MyString& str);
bool operator <=(const MyString& str);
bool operator >=(const MyString& str);
friend ostream& operator <<(ostream& os,const MyString&str);
friend istream& operator >>(istream& is,MyString&str);
};
int main()
{
MyString str1="Hello ";
MyString str2="world.";
cout<<str1+str2<<endl;
cout<<(str1[0]='0')<<endl;
cin>>str1;
cout<<str1<<endl;
return 0;
}
MyString::MyString(int n):_size(n){
_ptr=new char[n+1];
memset(_ptr,0,n+1);
}
MyString::MyString(char*str){
int n=strlen(str);
_size=n;
_ptr=new char[_size+1];
strcpy(_ptr,str);
}
MyString::MyString(const MyString&obj){
_size=;
_ptr=new char[_size+1];
strcpy(_ptr,);
}
int MyString::size()const{return _size;}
MyString& MyString::operator+(const MyString& str){
_size+=;
char*tmp=new char[_size+1];
strcpy(tmp,_ptr);
strcpy(tmp+strlen(_ptr),);
delete[]_ptr;
_ptr=tmp;
return *this;
}
返回类型类名::operator 运算符(参数列表)
char& MyString::operator[](i
运算符重载 来自淘豆网www.taodocs.com转载请标明出处.