• 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;

    }

  • 相关阅读:
    20155217 2016-2017-2《java程序设计》第一周学习总结
    20155217杨笛-安装虚拟机
    20155217-杨笛-c与java
    我所期望的师生关系
    jQ学习之实现全选全不选操作
    jQ学习之实现表格的隔行换色
    jQ学习之过滤选择器的测试
    jQ学习之层级选择器的测试
    jQ学习之基础选择器的测试
    jQ学习之实现图片的定时弹出
  • 原文地址:https://www.cnblogs.com/hbhzsysutengfei/p/3409506.html
Copyright © 2020-2023  润新知