无意识(寄
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)
{
if( s.p ) {
p = new char[strlen(s.p)+1];
strcpy(p,s.p);
}
else {
p = NULL;
}
}
void Copy(const char* s)
{
if(p)
delete []p;
if(s){
p = new char[strlen(s) + 1];
strcpy(p,s);
}
else
p = NULL;
}
friend ostream& operator<<(ostream& output,MyString& s)
{
output<<s.p;
return output;
}
/*void operator=(const char* s)
{//可以不写char*? 直接调用了类型转换构造函数没有
if(!s)
{
p=NULL;
}
else
{
p=new char[stlen(s)+1]
}
}*/
void operator=(const MyString& s)
{
if(this==&s)
{
return ;
}
if(s.p)
{
if(p)
{
delete [] p;
}
p=new char[strlen(s.p)+1];
strcpy(p,s.p);
}
else
{
p=NULL;
}
return ;
}
};
int main()
{
char w1[200],w2[100];
while( cin >> w1 >> w2) {
MyString s1(w1),s2 = s1;
MyString s3(NULL);
s3.Copy(w1);
cout << s1 << "," << s2 << "," << s3 << endl;
s2 = w2;//调用了类型转换构造函数
s3 = s2;
s1 = s3;
cout << s1 << "," << s2 << "," << s3 << endl;
}
}
友元函数定义 :既可以是不属于任何类的非成员函数,也可以是另一个类的成员函数,统称为友元函数。友元函数不是当前类的成员函数,而是独立于类的外部函数,但它可以访问该类所有的成员,包括私有成员、保护成员和公有成员。在类中声明友元函数时,需在其函数名前加上关键字friend,此声明可以放在公有部分、也可以放在保护和私有部分。友元函数可以定义在类部,也可以定义在类的外部。
MyString(const char * s)是构造函数更是类型转换函数,在s2=w2运行时,先将w2临时通过类型转换函数生成临时的w2的MyString类型,后将其通过void operator=(const MyString& s)将其赋值,实现深拷贝,浅拷贝容易出现delete多次的问题,若内部的指针new出来的空间,后因某种原因,该指针又要new一块空间,则应先要delete[]p 此为合理的编程