mooc openjudge 014 MyString对运算符重载的综合使用

#include <iostream>
#include <string>
#include <cstring>
using namespace std;
class MyString {
	char * p;
public:
	MyString(const char * s) {
		if( s) {
			p = new char[strlen(s) + 1];
			strcpy(p,s);
		}
		else
			p = NULL;

	}
	~MyString() { if(p) delete [] p; }

// 在此处补充你的代码
    MyString(MyString & s){//这个复制构造函数必须要写否则就报错了,不些就是逐个字节复制,导致指向同一片内存空间,但此处的析构函数又有delete,
        p=new char[strlen(s.p)+1];
        strcpy(p,s.p);
    }

    MyString & operator=(const MyString & s){
        if(p){
            delete []p;
        }
        p=new char [strlen(s.p)+1];
        strcpy(p,s.p);
        return *this;
    }

    MyString & operator=(const char *w ){
        if(p){
            delete [] p;
        }
            p=new char [strlen(w)+1];
            strcpy(p,w);
            return *this;

    }

    void Copy(const char *w){
        p=new char [strlen(w)+1];
        strcpy(p,w);
    }

    
   /* 用这个重载类型转换函数,或者用下面那个重载<<都是可以的
   operator char*(){
        return p;
    }
    */
    

    friend ostream & operator<<(ostream & o,MyString & s){//<<的重载只能通过全局函数,但此处通过友元的方法写在了里面
        cout<<s.p;
        return o;
    }

};
int main()
{
	char w1[200],w2[100];
	while( cin >> w1 >> w2) {//带有动态分配空间的,最好自己写一个复制构造函数,特别是还有个析构delete
		MyString s1(w1),s2 = s1;//这里这个=应该需要重载 
		MyString s3(NULL);
		s3.Copy(w1);//这里需要写这个copy函数
		cout << s1 << "," << s2 << "," << s3 << endl;//这里需要重载<<,或者重载一个强转
		s2 = w2;//这里=应该也需要重载
		s3 = s2;
		s1 = s3;
		cout << s1 << "," << s2 << "," << s3 << endl;
		
	}
}
`


这道题挺综合的,需要通过给出的main函数,来逐一分析到底需要在前面重载哪些运算符或者成员函数,顺藤摸瓜。
尤其是,这道题需要深拷贝,包括对=的两个重载以及自己需要写一个深拷贝的复制构造函数

上一篇:Python入门-异常处理


下一篇:C#的并集差集交集