笔试题string实现

笔试题string实现

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

class mystring{
public:
     mystring(const char *str = NULL);//构造函数
	 mystring(const mystring &str);//拷贝构造函数
	 ~mystring();//析构函数 
	 mystring &operator=(const mystring &str);//运算符重载	 
	 int size() const;//字符串实际大小,不包含结束符
	 const char *c_str() const;
	 mystring operator+(const mystring &str) const;//重载+
      
private:
     char *data;
	 int length;
};

mystring  mystring::operator+(const mystring &str) const {
	
	mystring newstr;
	newstr.length = length + str.size();
	newstr.data = new char[newstr.length + 1];
	strcpy(newstr.data, data);
	strcat(newstr.data, str.data);
	printf ("line:%d\n", __LINE__);
	cout << "this->data = " << newstr.data << endl;		
	return newstr;
}


mystring & mystring::operator = (const mystring &str) {
	if (this == &str)//检查自赋值
		return *this;
		
	if (data) 
		delete[] data;
	
	length = str.size();
	//length = strlen(str.data);
	data = new char[length + 1];
	strcpy(data, str.c_str());
	printf ("line:%d\n", __LINE__);
	cout << "this->data = " << this->data << endl;		
	
	return *this;
}

//通用构造函数
mystring::mystring(const char *str) {
	if (!str) {
		length = 0;
		data = new char[1];
		*data = '\0';
		
		printf ("line:%d\n", __LINE__);
	} else {
	    length = strlen(str);
        data = new char[length + 1];
        strcpy(data, str);	
        
        printf ("line:%d\n", __LINE__);	
        cout << "this->data = " << this->data << endl;		
	}
}

//拷贝构造函数
mystring::mystring(const mystring &str) {
	length = str.size();
	data = new char[length + 1];
	strcpy(data, str.c_str());	
	printf ("line:%d\n", __LINE__);
	cout << "s3 = " << this->data << endl;
}

//析构函数
mystring::~mystring() {
	delete []data;
	length = 0;	
	printf ("line:%d\n", __LINE__);
}

//计算大小
int mystring::size() const {
	
	return length;
}

//将string转c_str()
const char *mystring::c_str() const {
	return data;
}

int main() {
	mystring s;
    printf ("line:%d\n", __LINE__);
	
	char a[] = "hello";
    char b[] = "world!";
	//通用构造函数
	mystring s1(a),s2(b);
	//拷贝构造函数
	mystring s3(s1);
	//+重载
	mystring s5 = s1 + s2;
	//赋值函数
	s1 = s2; 
	//拷贝构造函数
	mystring s4 = s1;
	
	
	
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

屁小猪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值