侯捷-C++面向对象高级开发(上) 笔记09 string的简易实现

String.h部分

#ifndef  __MYSTRING__
#define  __MYSTRING__

#pragma warning(disable:4996)
#include<iostream>
#include<string.h>
#include<ostream>
using namespace std;


class String
{
private:
	char* m_date;
public:
	String(const char* cstr = 0);             //四个函数声明
	String(const String & str);
	String & operator = (const String & str);
	//String & operator +=(const String & str);
	~String();
	
	char * get_str() const
	{
		return m_date;
	}
};

inline
String::String(const char * cstr )
{
	if (cstr)               //如果传了值
	{
		m_date = new char[strlen(cstr) + 1];
		strcpy(m_date, cstr);
	}
	else
	{
		m_date = new char[1];
		*m_date = '\0';
	}
}

inline
String::String(const String & str)  //拷贝构造
{
	m_date = new char[strlen(str.m_date) + 1];
	strcpy(m_date, str.m_date);
}

inline 
String :: ~String()
{
	delete [ ] m_date;
}


//重载操作符=
inline 
String & String::operator =(const String & str)
{
	if (this == &str)  //判定是否自我赋值
	{
		return *this;	
	}

	delete[] m_date;
	m_date = new char[strlen(str.m_date) + 1];
	strcpy(m_date, str.m_date);
	return *this;
}

//重载<<

inline 
ostream & operator<<(ostream & os, const String & str)
{
	return os << str.get_str() << endl;
}


#endif // !__STRING__

String_test.cpp部分


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

using namespace std;

int main() 
{
	// 前两个离开作用域的时候会自动调用析构函数 c++会自动析构栈上的对象 函数退出的时候会析构
	String s1;
	// static在作用域结束后仍然存在 直到程序结束
	static String s2("hello");

	s1 = s2;
	// 但是*p是在堆上分配空间 需要手动释放
	// new 表示先分配内存 然后调用ctor
	String* p = new String("hello");
	// delete 释放了堆上的指针 指针释放之后系统会自动调用析构函数 释放p中的对象 
	// 先调用析构函数dtor 然后释放内存 先调用dtor析构内部申请的内存
	// String::~String(p);
	// operator delete(p); => free(p);
	delete p;

	// 以s1为蓝本 拷贝构造 
	String s3(s1);

	cout << s3 << endl;
	// 拷贝赋值  编译器会 实现拷贝赋值 拷贝构造 默认操作是浅拷贝是危险的
	s3 = s2;

	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值