面试的时候我们可能会经常碰到这个问题,所以我们需要复习一下这个问题。
由于时间要求,我们不可能写出std::string那样的功能,我们需要能够大体实现相关功能.
#include<iostream>
#include<cstdlib>
using namespace std;
class String
{
friend ostream& operator<<(ostream& os,String& str);
public:
String(const 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()
{
if (_str != NULL)
{
delete[] _str;
_str = NULL;
}
}
String& operator=(const String& str)//赋值运算符需要对引用进行修改以后才行。
{
if (this != &str)
{
delete[] _str;
_str = new char[strlen(str._str) + 1];
strcpy(_str, str._str);
}
return *this;
}
更加现代的一种,赋值运算符重载
//String& operator=(String str)
//{
// std::swap(_str, str._str);
//在这里进行了交换,交换完以后又利用函数当中的
//副本机制,把其中的给销毁了。
// return *this;
//
//}
private:
char *_str;
};
ostream& operator<<(ostream& os, String& str)
{
os << str._str;
return os;
}
int main()
{
String s1("123455");
String s2;
s2 = s1;
String s3(s1);
cout << s1 << s2 << endl;
cout << s3 << endl;
system("pause");
return 0;
}