#include <iostream>
using namespace std;
class TestString;
//extern ostream& operator<<(ostream& out, TestString& testString);
class TestString
{
friend ostream& operator<<(ostream& out, TestString& testString);
public:
TestString();
~TestString();
TestString(const char * charArray);
TestString& operator=(const char *charArray);
TestString& operator=(const TestString& testString);
TestString(const TestString& testString);
private:
char* m_myString;
int m_length;
};
TestString::TestString()
{
m_myString =NULL;
m_length = 0;
}
TestString::~TestString()
{
delete [] m_myString;
}
TestString::TestString(const char * charArray)
{
if(charArray == NULL)
{
m_myString = new char[1];
m_myString[0] = '\0';
m_length = 0;
}
else
{ m_length = strlen(charArray);
m_myString = new char[m_length];
memcpy((void*)m_myString,(void*)charArray,m_length);
}
}
TestString& TestString::operator=(const char *charArray)
{
if(m_myString)
{
delete [] m_myString;
m_myString = NULL;
m_myString = 0;
}
if(charArray == NULL)
{
m_myString = new char[1];
m_myString[0] = '\0';
m_length = 0;
}
else
{
m_length = strlen(charArray);
m_myString = new char[m_length];
memcpy((void*)m_myString,(void*)charArray,m_length);
}
return *this;
}
TestString& TestString::operator=(const TestString& testString)
{
//需要检测自赋值
if(this == &testString)
{
return *this;
}
else
{
delete [] m_myString;
m_length = testString.m_length;
m_myString = new char[testString.m_length];
memcpy((void*)m_myString,(void*)testString.m_myString,m_length);
return *this;
}
}
TestString::TestString(const TestString& testString)
{
m_length = testString.m_length;
m_myString = new char[m_length];
memcpy((void*)m_myString,(void*)testString.m_myString,m_length);
}
ostream& operator<<(ostream& out, TestString& testString)
{
for(int i=0;i!=testString.m_length;++i)
{
out<<*((char*)(testString.m_myString+i));
}
return out;
}
int main()
{
TestString test("ad");// = "abcd";
test = test;
TestString test2;
cout<<test<<endl;
cout<<test2<<endl;
test2 = test;
TestString test3(test2);
cout<<test3<<endl;
system("pause");
return 0;
}
实现string的默认构造函数,拷贝函数,c型字符串参数的构造函数,赋值构造函数,析构函数,重载输出操作符,测试
最新推荐文章于 2022-02-19 00:30:26 发布