C++ 进阶5 拷贝构造 深度复制 运算符重载

C++ 进阶5 拷贝构造 深度复制 运算符重载 20131026

例子: 运行环境是G++ 编译,

/*

 * main.cpp

 *

 *  Created on: 2013年10月26日

 *      Author: yangtfei

 */

#include <iostream>

#include <cstring>

#include <stdlib.h>

#include <stdio.h>

using namespace std;

class Base{

private:

    int val;

    char * str;

public:

    Base(const char * str, const int v){

        this->val = v;

        int len  = strlen(str);

        this->str = new char[len+1];

        strcpy(this->str,str);

    }

    Base(const Base & b){

        this->val = b.val;

        int len  = strlen(b.str);

        this->str = new char[len+1];

        strcpy(str, b.str);

    }

    Base& operator=(const Base& b){

        this->val = b.val;

        int len =  strlen(b.str);

        this->str = new char[len+1];

        strcpy(str,b.str);

        return *this;

    }

    ~Base(){

        delete this->str;

        cout << "Base::~Base()" << endl;

    }

    void printInfo(){

        cout << "val:" << this->val << ", name:" << this->str << endl;

    }

    void setName(const char * name){

        if(this->str!= NULL){

            delete str;

            str = NULL;

        }

        int len  = strlen(name);

        str = new char[len+1];

        strcpy(str,name);

    }

};

void getMemory(char ** p , int num){

    *p =(char*) malloc(num);

}

int main(){

    Base b("yang",10);

    Base c = b;

    Base d (b);

    b.printInfo();

    c.printInfo();

    d.printInfo();

    b.setName("teng");

    c.setName("fei");

    b.printInfo();

    c.printInfo();

    d.printInfo();

    return 0;

}

原文地址:https://www.cnblogs.com/hbhzsysutengfei/p/3409506.html