试验C++构造函数,析构函数,拷贝构造函数和赋值构造函数

                           试验C++构造函数,析构函数,拷贝构造函数和赋值构造函数 

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

using namespace std;

class student
{
public:
 student()
 {
  cout<<"default constructor is called!"<<endl;
  name=new char[1];
  name[0]='/0';
  age=0;
 }
 student(char* name,int age)
 {
  if(name==NULL)
  {
   this->name=new char[1];
   name[0]='/0';
  }
  else
  {
   this->name=new char[strlen(name)+1];
   strcpy(this->name,name);
   cout<<"constructing student:"<<this->name<<endl;
   this->age=age;
  }
 }
 student(const student& stu)
 {
  this->name=new char[strlen(stu.name)+strlen("copy of")+1];
  strcpy(this->name,stu.name);
  strcat(this->name,"copy of");
  cout<<"constructing student:"<<this->name<<endl;
  this->age=stu.age;
  
 }
 student& operator=(const student& stu)
 {
  if(this==&stu)  //检查自赋值用指针比较,不能用对象比较,对象比较函数未定义
   return *this;
  if(this->name)
   delete this->name;
  this->name=new char[strlen(stu.name)+strlen("===construct")+1];
  strcat(stu.name,"===construct");
  strcpy(this->name,stu.name);
  cout<<"constructing student by ====!"<<endl;
  this->age=stu.age;
  return *this;
 }
 ~student()
 {
  cout<<"destructing student:"<<this->name<<"age:"<<this->age<<endl;

  if(this->name)
   delete this->name;
  this->name=NULL;
 }
private:
 char* name;
 int age;
};
student test(student s)     //实参传递给形参的时候调用拷贝构造函数
{
 cout<<"in the test function!"<<endl;
 student s2("temp",22);
 //返回临时对象前先拷贝构造一个临时对象,然后复制给实参
 //返回栈空间,程序本身有问题。但是拷贝构造函数将原来的对象在一个新空间构造,
 //所以不存在内存泄露。
 return s2; //好像编译器调用析构函数去析构自己产生的临时对象出错
}
int main(int argc, char* argv[])
{
 cout<<"start the programing!"<<endl;
 student stu("roger",11);
 cout<<"to execute the test()!"<<endl;
 //int i=0;
 //while(i++<10000000)
 student s3("gugy",23);
 s3=test(stu);   //调用赋值函数
 cout<<"exit the programing!"<<endl;
 return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值