第八章作业

#include "CMyString.h"//CMyString.cpp
using namespace std;
CMyString CMyString::operator+(CMyString &obj)
{
	cout<<"重载运算符+"<<endl;
	char *p=new char[m_length];
	for(int k=0;k<m_length;k++)
		p[k]=m_p[k];
	delete []m_p;
	m_p=new char[m_length+obj.m_length];
	for(int i=0;i<m_length;i++)
	{
		m_p[i]=p[i];
		//cout<<m_p[i]<<endl;
	}
	delete []p;

	for(int j=m_length;j<m_length+obj.m_length;j++)
	{
		m_p[j]=obj.m_p[j-m_length];//注意j要减去length
		//cout<<m_p[j]<<endl;
	}
	m_length=m_length+obj.m_length;
	//cout<<"m_length="<<m_length;
	return *this;
}
void CMyString::operator =(CMyString &obj)
{
	cout<<"重载运算符="<<endl;
	delete []m_p;
	m_length=obj.m_length;
	m_p=new char[m_length];
	for(int i=0;i<m_length;i++)
		m_p[i]=obj.m_p[i];
}


#ifndef _CMYSTRING_H_//CMyString.h
#define _CMYSTRING_H_
#include <iostream>
using namespace std;

class CMyString
{
public:
	CMyString(int length,char *p)
	{
		cout<<"构造string!"<<endl;
		m_length=length;
		m_p=new char[length];
		for(int i=0;i<length;i++)
		{
			m_p[i]=p[i];
		}
		//m_p[i]='\0';
		
	}
	CMyString(CMyString &obj)//拷贝构造函数没有返回值eg。CPoint(CPoint &obj)
	{
		cout<<"拷贝构造函数!String"<<endl;
		m_length=obj.m_length;
		//delete []m_p;
		m_p=new char[m_length];
		for(int i=0;i<obj.m_length;i++)
			m_p[i]=obj.m_p[i];
	}
	void ShowCMyString()const
	{
		for(int i=0;i<m_length;i++)
			cout<<m_p[i];
		cout<<endl;
	}
	~CMyString()
	{
		delete []m_p;
		cout<<"析构string!"<<endl;
	}
	int GetLength()
	{
		return m_length;
	}
	char* GetP()
	{
		return m_p;
	}
	CMyString operator+(CMyString &obj);
	void operator =(CMyString &obj);
private:
	int m_length;
	char *m_p;
};
#endif


#include "CMyString.h"//smain.cpp
#include <string>
using namespace std;
char GetChar()
{
	char ch;
	while((ch=cin.get())=='\n')
	{;}
	//cout<<"ch="<<ch<<"!!"<<endl;
	return ch;
}
void main()
{
	char *p;
	cout<<"input the length:";
	int length;
	cin>>length;
//	cin.get();
	cout<<"input the string:";
	//string b;
	//cin>>b;
	p=new char[length];
	
	for(int i=0;i<length;i++)
	{
		p[i]=GetChar();
	}
	CMyString a(length,p);
	a.ShowCMyString();
	CMyString b(a);
	b.ShowCMyString();
	CMyString c(b);
	c=a+b;
	c.ShowCMyString();
	delete []p;
	//cout<<length;

}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值