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

http://tangfeng.iteye.com/blog/89140

 

试验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;
}

posted @ 2012-11-07 23:32  小心小意  阅读(215)  评论(0编辑  收藏  举报