赋值运算符重载:字符串直接赋值给对象

#include"iostream"
using namespace std;
class String{
private:
    char *str;
public:
    String() :str(NULL){}
    const char*c_str(){ return str; }
    char*operator=(const char*s);
    ~String(){};
    String & operator=(const String&);  
    String(String &s);
};
char* String::operator=(const char*s){
    if (str) delete[]str;
    if (s){
        str = new char[strlen(s) + 1];
        strcpy(str, s);
    }
    else
        str = NULL;
    return str;
}
String::String(String &s){
    if (s.str){
        str = new char[strlen(s.str) + 1];
        strcpy(str, s.str);
    }
    else{
        str = NULL;
    }
}
String& String::operator = (const String& s){
    if (str == s.str) return *this;
    if (str) delete[]str;
    if (s.str){
        str = new char[strlen(s.str) + 1];
        strcpy(str, s.str);
    }
    else{
        str = NULL;
    }

    return *this;
}
int main(){
    String s;
    s = "Hello";
    cout << s.c_str() << endl;
    return 0;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容