zoukankan      html  css  js  c++  java
  • 构造函数、析构函数、拷贝构造函数、赋值函数

    一个小例子,说明类的几大函数:

    #include <iostream>
    using namespace std;
    class c_test{
        public:
            c_test();
            c_test(int para_a=3,string str="original");
            c_test(const c_test & other);
            ~c_test(void);
            c_test & operator =(const c_test & other);
        private:
            string name;
            int num;
    };
    c_test::c_test(){
    }
    c_test::c_test(int para_a,string str){
        this->num=para_a;
        this->name=str;
        cout<<"I am in constructor, my name is "<<this->name<<", my value is "<<this->num<<endl;
    }
    c_test::c_test(const c_test & other){
        this->num=other.num;
        this->name=other.name+" copy";
        cout<<"I am in copy constructor, my name is "<<this->name<<", my value is "<<this->num<<endl;
    }
    c_test & c_test::operator=(const c_test & other){
        this->num=other.num;
        this->name=other.name;
        cout<<"I am in operator =, my name is "<<this->name<<", my value is "<<this->num<<endl;
        return *this;
    }
    c_test::~c_test(void){
        cout<<"I am in destructor, my name is "<<this->name<<", my value is "<<this->num<<endl;
    }
    main(){
        int a;
        int b;
        c_test obj_a(3,"a");
        c_test obj_b(obj_a);//调用拷贝构造函数
        c_test * p_a=new c_test(333,"s");
        c_test * p_b=new c_test(2,"b");
        *p_a=obj_a;//调用赋值函数
        printf("0X%08X\n",&a);
        printf("0X%08X\n",&b);
        printf("0X%08X\n",p_a);
        delete p_b;

  • 相关阅读:
    NOIP2014D2T2寻找道路(Spfa)
    【割点】【割边】tarjan
    NOIP2013D1T3货车运输(最大生成树+倍增lca)
    lca最近公共祖先(模板)
    人生第一次hash
    【模板】Tarjan求强连通分量
    【模板】链式前向星+spfa
    二叉树的三种遍历
    hdu 3549 最大流
    hdu 1532&&poj1273 基础最大流
  • 原文地址:https://www.cnblogs.com/welkinwalker/p/1950939.html
Copyright © 2011-2022 走看看