i6lan 分享题目的网站
试一试站内搜索 题目类型:问答题

应急计划是核电站核安全“多层保
关于外甥的歇后语“吴道爷的外甥
正确的防护手段可有效预防新型冠
C类火灾是指________。
涉密部门或项目负责人,对本部门

编写类String的构造函数、析构函数和赋值函数和测试程序。已知类String的原型为:


#include <iostream.h>

#include <string.h>

class String

{public:

String(const char *str=NULL); // 普通构造函数

String(const String &other); // 拷贝构造函数

~String(); // 析构函数

String & operator=(const String &other); // 赋值函数

void show()

{cout<<m_data<<endl;

}

private:

char *m_data; // 用于保存字符串

};


答案:String::~String()

{delete[]m_data;//由于m_data是内部数据类型,也可以写成delete m_data;

}

String::String(const char *str)

{if(str==NULL)

{m_data=new char[1];//若能加NULL判断则更好

*m_data=\0;

}

else

{int length=strlen(str);

m_data=new char[length+1]; //若能加NULL判断则更好

strcpy(m_data, str);

}

}

String::String(const String &other)

{int length=strlen(other.m_data);

m_data=new char[length+1];//若能加NULL判断则更好

strcpy(m_data, other.m_data);

}

String & String::operator=(const String &other)

{if(this==&other)

return *this;

delete[]m_data;

int length=strlen(other.m_data);

m_data=new char[length+1];//若能加NULL判断则更好

strcpy(m_data, other.m_data);

return *this;

}

void main()

{String str1("aa"),str2;

str1.show();

str2=str1;

str2.show();

String str3(str2);

str3.show();

}

上一题 下一题

CopyRight©i6lan.com 关于本站
蜀ICP备2021017061号-1

川公网安备 51010402001278号