String类:构造函数,拷贝构造函数

#include <iostream>
#include <string.h>
using namespace std;

class String
{
public:
	String(const char * str = NULL); //默认参数只需在函数声明时注明,函数定义时不需要
	String(const String &other);
	String & operator=(const String &other);
	~String(void);
	void output() { cout << m_data << endl; }
private:
	char *m_data; //用于保存字符串
};

String::String(const char * str)
{
	if (NULL == str)
	{
		m_data = new char[1];
		*m_data = '\0';
	}
	else
	{
		m_data = new char[strlen(str)+1];
		strcpy(m_data, str);
	}
	cout << "Constructor is called" << endl;
}

String::String(const String &other)
{
	m_data = new char[strlen(other.m_data)+1];
	strcpy(m_data, other.m_data);
	cout << "Copy constructor is called" << endl;
}

String& String::operator=(const String &other)
{
	if (this == &other)  //不能写为if(*this == other),因为没有重载==,不能将两个类的对象做对比
	{
		return *this;
	}

	delete [] m_data;

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

	cout << "Assignment operator is called" << endl;
	return *this;
}

String::~String(void)
{
	delete []m_data;
	cout << "Destructor is called" << endl;
}
int main()
{
	const char *c="hello";
	String s(c);   //Constructor is called
	s.output();
	String s2 = s; //Copy constructor
	String s3(s2); //Copy constructor
	s3 = s;        //Assignment operator

	return 0;
}

输出:

Constructor is called
hello
Copy constructor is called
Copy constructor is called
Assignment operator is called
Destructor is called
Destructor is called
Destructor is called


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值