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


    #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
  • 相关阅读:
    Shell-01-脚本开头实现自动添加注释
    Linux中通过SHELL发送邮件
    linux服务器修改密码登录Failed to restart ssh.service: Unit ssh.service not found
    ffmpeg+java实现五秒钟剪辑80个视频
    Vue学习-watch 监听用法
    springboot添加定时任务
    Spring异常:java.lang.NoClassDefFoundError: org/springframework/core/OrderComparator$OrderSourceProvider
    多线程实战-龟兔赛跑
    Git分支管理(二)
    android studio bug : aidl is missing 解决方案
  • 原文地址:https://www.cnblogs.com/CodeWorkerLiMing/p/10997822.html
Copyright © 2020-2023  润新知