码迷,mamicode.com
首页 > 编程语言 > 详细

C++构造函数实例——拷贝构造,赋值

时间:2019-06-10 15:35:38      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:构造函数   运行   div   mes   private   operator   iostream   引用   main   

#define _CRT_SECURE_NO_WARNINGS //windows系统 
#include <iostream> 
#include <cstdlib> 
#include <cstring>
using namespace std;

class student 
{
private:
    char *name;
    int age;
public:
    student(const char *n = "no name", int a = 0)   
    {
        name = new char[100];                 // 比malloc好!         
        strcpy(name, n);
        age = a;
        cout << "构造函数,申请了100个char元素的动态空间" << endl;
    }
    student & operator=(const student &s) 
    {    
        strcpy(name, s.name);
        age = s.age;
        cout << "赋值函数,保证name指向的是自己单独的内存块" << endl;
        return *this;    //返回 “自引用”     
    }    
    student(const student &s) 
    {               // 拷贝构造函数 Copy constructor     
        name = new char[100];
        strcpy(name, s.name);
        age = s.age;
        cout << "拷贝构造函数,保证name指向的是自己单独的内存块" << endl;
    }
    void display(void)
    {
        cout << name << ", age " << age << endl;
    }
  virtual ~student() 
    {                             // 析构函数     
        cout << "析构函数,释放了100个char元素的动态空间" << endl;
        delete[] name;                          // 不能用free!         
    }
};
int main() 
{
    //student s;    //编译错误,类中实现了构造函数,因此,需要有参数
    student k("John", 56);
    student mm(k);        //拷贝构造函数
    
    student m("lill", 666);
    m.display();

    m = k;                //赋值函数
    k.display();
    mm.display();

    return 0;
}

运行结果:

构造函数,申请了100个char元素的动态空间
拷贝构造函数,保证name指向的是自己单独的内存块
构造函数,申请了100个char元素的动态空间
lill, age 666
赋值函数,保证name指向的是自己单独的内存块
John, age 56
John, age 56
析构函数,释放了100个char元素的动态空间
析构函数,释放了100个char元素的动态空间
析构函数,释放了100个char元素的动态空间

const char *n = "no name",必须添加const

 

C++构造函数实例——拷贝构造,赋值

标签:构造函数   运行   div   mes   private   operator   iostream   引用   main   

原文地址:https://www.cnblogs.com/CodeWorkerLiMing/p/10997822.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!