zoukankan      html  css  js  c++  java
  • 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;

    }

  • 相关阅读:
    HugePage简介和KVM中使用HugePage
    Linux HugePage特性
    tcpreplay工具安装使用
    libpcap丢包原理分析及Fedora 9 内核2.6.25.14下安装PF-RING的详细过程
    linux fedora 14(内核2.6.35.6) PF_RING+libpcap 极速捕获千兆网数据包,不丢包
    CPU亲和力
    Linux中link,unlink,close,fclose详解
    LINUX内核升级-更新网卡驱动
    2019-2020-2 20175319江野《网络对抗技术》Exp9 Web安全基础
    2019-2020-2 20175319江野《网络对抗技术》Exp8 Web基础
  • 原文地址:https://www.cnblogs.com/hbhzsysutengfei/p/3409506.html
Copyright © 2011-2022 走看看