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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值