zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    ural1018(树形dp)
    hdu1011(树形dp)
    poj1463(树形dp)
    poj1655(树形dp)
    poj1155(树形dp)
    hdu2196(树形dp)
    hdu1520(树形dp)
    hdu2126(求方案数的01背包)
    运用bootstrap框架的时候 引入文件的问题
    动态的改变标签内的src属性
  • 原文地址:https://www.cnblogs.com/CodeWorkerLiMing/p/10997822.html
Copyright © 2011-2022 走看看