#include<iostream>
#include<string.h>
using namespace std;
class String;
class String{
friend istream& operator>>(istream& is,String& s1);
friend ostream& operator<<(ostream& os,const String& s2);
public:
String():str(0),len(0){};
String(char *_str);
String(const String &s);
~String();
String operator=(const String& s);
String operator=(char *_str);
String operator+(const String &s);
String operator+(char *_str);
int operator>(const String& );
int find(String &);
int length(){
return len;
}
char get_str(){
return *str;
}
private:
char* str;
int len;
};
String::String(char *strc){
len=strlen(strc)+1;
str=new char[len+1];
strcpy(str,strc);
}
String::String(const String &s):len(s.len){
str=new char[len+1];
strcpy(str,s.str);
}
String::~String(){
if(str)
delete[] str;
}
istream& operator>>(istream& is,String& s1){
is>>s1.str;
return is;
}
ostream& operator<<(ostream& os,const String& s2){
os<<s2.str;
return os;
}
String String::operator =(const String &o){
delete [] this->str;
this->str=new char[o.len+1];
strcpy(this->str,o.str);
return *this;
}
String String::operator=(char * _str)
{
delete [] this->str;
this->str = new char[strlen(_str)+1];
strcpy(this->str,_str);
return *this;
}
String String::operator +(char *_str){
String s;
s.len=len+strlen(_str);
s.str=new char[s.len];
strcpy(s.str,this->str);
strcat(s.str,str);
return s;
}
String String::operator +(const String& d){
return strcpy(this->str,d.str);
}
String::operator >(const String& b){
return strcmp(this->str,b.str);
}
int main()
{
String s1,s2,s3;
cin>>s1>>s2;
s3=s1+s3;
cout<<s3<<endl;
//for(int i=0;i<s3.length();i++)
//cout<<s3[i];
cout<<endl;
//比较两个字符串的大小,按字符顺序
if(s1>s2)
cout<<s1<<"is more large than "<<s2<<endl;
//输出s2在s3中位置
//cout<<s3.find(s2);
return 0;
}
编译时候结果如下:(xp+vc++6.0)
Compiling...
string.cpp
E:\xuxu\1\string.cpp(50) : error C2248: 'str' : cannot access private member declared in class 'String'
E:\xuxu\1\string.cpp(32) : see declaration of 'str'
E:\xuxu\1\string.cpp(54) : error C2248: 'str' : cannot access private member declared in class 'String'
E:\xuxu\1\string.cpp(32) : see declaration of 'str'
E:\xuxu\1\string.cpp(117) : error C2593: 'operator >>' is ambiguous
E:\xuxu\1\string.cpp(119) : error C2593: 'operator <<' is ambiguous
E:\xuxu\1\string.cpp(125) : error C2593: 'operator <<' is ambiguous
Error executing cl.exe.
string.obj - 5 error(s), 0 warning(s)
我有点搞不顶了