复习构造函数和赋值函数

 类SString的原型为:

class SString 
{
public:
 SString &operator=(const SString &other);//赋值构造函数
 SString(const SString &other);//拷贝构造函数
 SString(const char *str=NULL);//构造函数
 virtual ~SString(void);//析构函数
 void display();

private:
 char * m_data;
};

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

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

/*普通构造函数可以简单的根据一个字符串常量创建一个SString对象,

仅需要为变量分配足够的内存,再将字符串常量复制到这块内存即可*/

SString::SString(const char *str )
{
 if(NULL==str)
 {
  m_data=new char[1];
  *m_data='/0';
 }
 else
 {
  int length=strlen(str);
  m_data=new char[length+1];
  strcpy(m_data,str);
 }
 cout<<"call constructor"<<endl;
}

/*拷贝构造函数作用:

1.用户定义类型需要分配系统资源时。

2.在函数调用时以传值方式传递一个SString参数。

3.一个函数以值的形式返回SString对象时实现了“返回时赋值”

*/

SString::SString(const SString &other)
{
 int length=strlen(other.m_data);
 m_data=new char[length+1];
 strcpy(m_data,other.m_data);
 cout<<"call copyconstructor"<<endl;
}
SString::~SString(void)
{
 delete []m_data;
}

//赋值函数:实现字符串传值活动

/**/

SString &SString::operator=(const SString &other)
{
 if(this==&other)
  return *this;
 delete []m_data;//释放原有内存资源
 int length=strlen(other.m_data);
 m_data=new char[length+1];
 strcpy(m_data,other.m_data);
 cout<<"call operatorconstructor"<<endl;
 return *this;
}
void SString::display()
{
 cout<<m_data<<endl;
}

void main()
{
 SString str("hello");
 SString s2=str;
 SString s3;
 s3=str;
 str.display();
 s2.display();
 s3.display();
}

 

 

程序调试时的错误:

1.修改类名时,没有修改文件夹下头文件的名字

错误:fatal error C1083: Cannot open include file: 'SString.h': No such file or directory

2.操作符重载时operator而非operate

3.使用默认值的参数在声明时指定默认值,在定义时不需要指定。

错误:error C2572: 'SString::SString' : redefinition of default parameter : parameter 1

4.c++中默认的空指针是null,如用NULL表示空指针则需要包含头文件<window.h>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值