您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
String类的代码:
class String
{
public:
String(char* str="")
{
_str = new char[strlen(str) + 1];
strcpy(_str, str);
}
String(const String& str)
{
_str = new char[strlen(str._str) + 1];
strcpy(_str, str._str);
}
~String()
{
delete[] _str;
}
String& operator=(const String& str)
{
if (&str == this)
return *this;
delete[] _str;
_str = new char[strlen(str._str) + 1];
strcpy(_str, str._str);
return *this;
}
bool operator==(const String& str)
{
return strcmp(_str, str._str) == 0;
}
friend ostream& operator<<(ostream& o,String& str)
{
o << str._str;
return o;
}
private:
char* _str;
};包括构造函数,拷贝构造函数,析构函数,算数运算符重载。
下面是测试代码:
String s1 = "hello"; String s2 = "world"; String s3 = "o"; cout << "s1=" << s1 << endl; cout << "s2=" << s2 << endl; cout << "s3=" << s3 << endl; cout << endl; String s4(s1); String s5(s1); String s6(s1); s5 = s2; cout << "s4=" << s4 << endl; cout << "s5=" << s5 << endl; cout << (s4 == s5) << endl; cout << (s4 == s6) << endl;
测试结果:

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。