![]() |
#2
rjsp2012-12-08 13:38
随手改了一下
但因为你这段代码中杂七杂八的错误太多,可能没改全,请见谅 ![]() #include <iostream> #include <cstring> class String { public: String( const char* str=NULL ) : str_(NULL) { if( str ) { str_ = new char[strlen(str)+1]; strcpy(str_, str); } } String( const String& other ) : str_(NULL) { if( other.str_ ) { str_ = new char[strlen(other.str_)+1]; strcpy(str_, other.str_); } } String& operator=( const String& other ) { if( this != &other ) { delete[] str_; str_ = other.str_; if( other.str_ ) { str_ = new char[strlen(other.str_)+1]; strcpy(str_, other.str_); } } return *this; } ~String() { delete[] str_; } operator const char*() const { return str_ ? str_ : ""; } String& operator+=( const String& other ) { if( !other.str_ ) return *this; if( !str_ ) { str_ = new char[strlen(other.str_)+1]; strcpy(str_, other.str_); return *this; } size_t len1 = strlen(str_); size_t len2 = strlen(other.str_); char* buffer = new char[len1+len2+1]; strcpy(buffer,str_); strcpy(buffer+len1,other.str_); delete[] str_; str_ = buffer; return *this; } bool operator!=( const String& other) const { return strcmp((const char*)str_, (const char*)other.str_) != 0; } private: char* str_; }; std::ostream& operator<<( std::ostream& out, const String& str ) { return out << (const char*)str; } using namespace std; int main() { String a = "good student"; String b = "good"; b += "student"; if( a != b ) { cout<<"not same"<<endl; } char str[100]; strcpy( str, (const char*)a ); cout << str << endl; return 0; } |
#include<iostream>
#include<cstring>
using namespace std;
class String
{
private:
char* _str;
public:
String(char*str=NULL):_str(str)//构造函数
{
if(_str!=NULL)
_str = new char[strlen(str)+1];
strcpy(_str,str);
}
String(const String& other) : _str(other._str)//拷贝构造函数
{
if (other._str != NULL)
{
_str = new char[strlen(other._str)+1];
strcpy(_str, other._str);
}
}
~String()//析构函数
{
delete[] _str;
}
public:
friend ostream& operator<<(ostream& out,String& str)//“<<”运算符重载
{
out<<str._str;
return out;
}
String operator+=(String other)//"+="运算符重载
{
int len = strlen(_str)+strlen(other._str);
if(len==0)
{
return *this;
};
char* buffer = new char[len+1];
strcpy(buffer,_str);
strcat(buffer,other._str);
delete[] _str;
_str = buffer;
return *this;
}
bool operator!=(String other)//"!="运算符重载
{
if(strcmp(_str,other._str)==0)
return true;
else
return false;
}
};
void main()
{
String a="good student";
String b="good";
b+="student";
if(a!=b)
{
cout<<"not same"<<endl;
};
char str[100];
strcpy(str,(const char*)a);//这条语句通不过,在类中加什么操作能让编译通过?
cout<<str<<endl;
}