复习构造函数和赋值函数

来源:互联网 发布:php文件上传错误代码 编辑:程序博客网 时间:2024/05/17 01:11

 类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>

原创粉丝点击