|
it is depend on which compiler you uesed. When you use gcc, you will get error.
strictly speaking, you should define your copy constructor and assignment function in this form
Classname(const Classname & object); // copy constructor
// pay attention to "const", you should not forget this keyword
Classname & operator=(const Classname & object); // assignment
// pay attention to "const", you should not forget this keyword
I have his class rewritten, take a look.
程序代码:
#include <iostream>
using namespace std;
class String
{
public:
String()
{
inside= new char[50];
inside[49] = '\0';
}
String(const char * get)
{
int length = strlen(get);
inside = new char[length + 1];
strcpy(inside, get);
inside[length] = '\0';
}
String(const String & s1) // this is a copy constructor,
// it must defined it with using keyword "const",
// when you write your code strictly.
// with keyword const to
// tell your compiler,
// this parameter will be just used but not changed.
{
int size = strlen(s1.inside) + 1;
inside = new char[size];
strcpy(inside, s1.inside);
inside[size-1] = '\0';
}//ok
int find(String & s2);
int length();//ok
~String ()
{
if(inside)
delete [] inside;
}
String & operator=(const String & c1);//ok
String & operator +(const String & c2);//ok
friend istream& operator >>(istream &cin,String &o1);//ok
friend ostream& operator <<(ostream &cout,String &o2);//ok
bool operator > (String c3);
bool operator < (String c4);
char operator [](int x);//ok
private:
char *inside;
};
int String::find(String & s2)
{
if(s2.length()>length())
return -1;
else
{
int t=0,i=0;
for(;i<length(),t<s2.length();i++)
if(inside[i]==s2.inside[t])
t++;
if(t==s2.length())
return i-t;
else
return -1;
}
}
int String::length()
{
return strlen(inside);
}
String & String::operator=(const String & c1)
{
if((strcmp(inside, c1.inside) == 0) && inside == c1.inside)
return *this;
int size = strlen(c1.inside) + 1;
inside = new char[size];
strcpy(inside, c1.inside);
inside[size - 1] = '\0';
return *this;
}
String & String::operator +(const String & c2)
{
int size = length() + strlen(c2.inside) + 1;
char * temp = new char[size];
strcpy(temp, inside);
strcat(temp, c2.inside);
inside = temp;
return *this;
}
istream& operator >>(istream& cin,String& o1)
{
cin>>o1.inside;
return cin;
}
ostream& operator <<(ostream& cout,String& o2)
{
cout<<o2.inside;
return cout;
}
bool String::operator >(String c3)
{
if(strcmp(inside,c3.inside)==1)
return true;
else
return false;
}
bool String::operator <(String c4)
{
if(strcmp(inside,c4.inside)==-1)
return true;
else
return false;
}
char String::operator [](int x)
{
return *(inside+x);
}
int main()
{
char c[] = "hello 000 world";
char c1[] = "wor";
String s1(c);
String s2(c1);
String s3 = s1 + s2;
cout<<s3<<endl;
for(int i=0;i<s3.length();i++)
cout<<s3[i];
cout<<endl;
if(s1>s2)
cout<<s1<<" is more lager than "<<s2<<endl;
cout<<s3.find(s2);
return 0;
} |
|