zoukankan      html  css  js  c++  java
  • 试验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;
    }

  • 相关阅读:
    IDEA永久激活方法
    idea在本地调试,spark创建hiveContext的时候报错
    MVC里面调用webservice
    log4net配置
    Linq 使用skip和take分页
    ASP.NET页面之间传递值的几种方式
    C#操作redis
    C#知识点:I/O
    C#知识点:ref和Out关键字浅谈
    C#知识点:反射
  • 原文地址:https://www.cnblogs.com/wb118115/p/2759665.html
Copyright © 2011-2022 走看看