1、使用strcpy函数,m_str无需初始化(用\0初始化),strcpy会把源字符串的\0也复制到目的字符串;
2、析构函数中,要避免野指针问题,将m_str=NULL;
3、操作符<<重载时,为了符合平常使用习惯采用友元函数实现,就不能作为类成员函数定义;
4、ostream类没有拷贝构造函数,无法调用,返回值不能用ostream,必须返回引用类型ostream&;类似的ofstream类等没有拷贝构造函数或者拷贝构造函数是私有的,一样必须返回引用类型;
5、拷贝构造函数和赋值函数区别在于,赋值函数已经初始化,而拷贝构造函数是初始化时调用的。
#include "stdafx.h"
#include<iostream>
using namespace std;
class MyString
{
public:
MyString(char* str);
MyString(const MyString& str);
MyString& operator=(const MyString& str);
~MyString();
char operator[](int i);
MyString& operator+=(const MyString& str);
MyString& operator+=(char* str);
char* GetStr();
friend char* GetStr1(MyString str);//VC6.0编译器使用STL,则友元函数无法访问私有成员,VS不会
friend ostream& operator<<(ostream&out,MyString& str);//为了符合平常使用习惯采用友元函数实现
protected:
private:
char* m_str;
};
MyString::MyString(char* str)
{
if (str==NULL)
{
m_str=new char[1];
*m_str='\0';//注意加个\0
}
m_str=new char[strlen(str)+1];
strcpy(m_str,str);//使用strcpy,m_str无需初始化,strcpy会把源字符串的\0也复制到目的字符串
}
MyString::MyString(const MyString& str)
{
m_str=new char[strlen(str.m_str)+1];
strcpy(m_str,str.m_str);
}
MyString& MyString::operator=(const MyString& str)
{
if (this==&str)//同一个地址
{
return *this;
}
delete[] m_str;
m_str=new char[strlen(str.m_str)+1];
strcpy(m_str,str.m_str);
return *this;
}
MyString::~MyString()
{
if (m_str!=NULL)//
{
delete[] m_str;
m_str=NULL;//避免野指针问题
}
}
char MyString::operator[](int i)
{
return *(m_str+i);
}
MyString& MyString::operator+=(const MyString& str)
{
char* temp=new char[strlen(m_str)+1];
strcpy(temp,m_str);
delete[] m_str;
m_str=new char[strlen(temp)+strlen(str.m_str)+1];
strcpy(m_str,temp);
strcat(m_str,str.m_str);
//cout << strlen(m_str) << endl;
delete[] temp;
return *this;
}
MyString& MyString::operator+=(char* str)
{
if (str==NULL)
{
return *this;
}
char* temp=new char[strlen(m_str)+1];
strcpy(temp,m_str);
delete[] m_str;
m_str=new char[strlen(temp)+strlen(str)+1];
strcpy(m_str,temp);
strcat(m_str,str);
//cout << strlen(m_str) << endl;
delete[] temp;
return *this;
}
char* MyString::GetStr()
{
return m_str;
}
char* GetStr1(MyString str)//友元函数非类成员函数,需要借助一个MyString参数才能访问类成员
{
return str.m_str;
}
ostream& operator<<(ostream&out,MyString& str)//ostream类没有复制构造函数,无法调用,必须返回引用类型
{
out << str.m_str;
return out;
}
int main(){
MyString str1=MyString("abc");
cout << str1.GetStr() << endl;
MyString str2=str1;//拷贝构造函数
cout << str2.GetStr() << endl;
MyString str3("ABC");
str3=str1;//赋值函数
cout << str3.GetStr() << endl;
cout << "第一个字符:" << str1[0] << endl;//测试“下标”
cout << str1 << endl;//测试<<运算符重载
str1+=str3;
str2+="def";
return 0;
}