实现一个string类,包括构造、析构、拷贝构造及operator= 函数

C++面试经常会出这样的题,以下是参考网上以及个人的一点理解:
MyString.h
#include<iostream>  
using namespace std;

class MyString
{
public:
	//MyString(void);
	MyString(const char* str = NULL);		//定义些函数后,不能定义MyString(void);函数,否则构造无参数对象时,构造函数调用不明确,产生错误
	MyString(const MyString& other);
	~MyString(void);
	MyString& operator = (const MyString& other);

	bool operator==(const MyString &str);  
	friend ostream& operator<<(ostream& o,const MyString &str); 
private:
	char* m_data;
};

MyString.cpp

#include "MyString.h"
#include <string>

//MyString::MyString(void)
//{
//	m_data = new char[1];  
//	*m_data='\0';  
//	//m_data = NULL;		//这样也行吧?
//}

MyString::MyString(const char *str)
{
	if (str == NULL)
	{  
		m_data = new char[1];  
		*m_data='\0';  
	}
	else
	{  
		int len=strlen(str);  
		m_data = new char[len+1];  
		strcpy(m_data,str);  
	} 
}

MyString::MyString(const MyString &other)
{
	int len = strlen(other.m_data);  
	m_data = new char[len+1];  
	strcpy(m_data,other.m_data);  
}

MyString::~MyString(void)
{
	delete []m_data;
	m_data = NULL;
}

MyString& MyString::operator=(const MyString &other)
{
	if (this == &other)  
		return *this;  

	delete []m_data;

	int len = strlen(other.m_data);  
	m_data = new char[len+1];  
	strcpy(m_data,other.m_data);  

	return *this;
}

bool MyString::operator==(const MyString& str)
{
	 return strcmp(m_data,str.m_data) == 0;
}

//注意友元函数定义时不要friend,而且不要MyString::
ostream& operator<<(ostream& o,const MyString& str)
{
	o<<str.m_data;  
	return o; 
}

#include "MyString.h"

void main(void)
{
	MyString s1 = "hello";  
	MyString s2 = s1;	//这是对象初始化,等效于MyString s2(s1),会调用类的拷贝构造函数
	MyString s3;
	s3 = s1;		//这是赋值,注意与MyString s2 = s1;不同,会调用 =重载函数
	MyString s4 = "hello";  
	cout<<"s1 = "<<s1<<endl;  
	cout<<"s2 = "<<s2<<endl;  
	cout<<boolalpha<<(s4 == s1)<<endl;

	getchar();
}

运行结果:
s1 = hello
s2 = hello
true
请按任意键继续. . .


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值