zoukankan      html  css  js  c++  java
  • Copy Control Example

    复制构造函数, 赋值操作符 operator = ,析构函数 总称为复制控制 (Copy Control)

    e.g.:

    Code:

    #include <iostream>
    
    using namespace std;
    
    class T{
    public:
        T(){ cout<<"T constructor."<<endl; }
        T(const T& tobj){
            cout<<" T copy construct from T:"<<&tobj<<endl;
            t=tobj.t;
        }
        //若声明为explicit,则隐式调用
         /*explicit */
        T(int tmp):t(tmp){
             cout<<"T constructor from int."<<tmp<<endl;
        }
        ~T(){   cout<<"T destructor. instance:"<<(int)this<<",t value:"<<t<<endl;   }
        T& operator =(const T& tobj){
            cout<<" operator =, from:"<<hex<<&tobj<<",to:"<<hex<<(int)this<<endl;
            this->t=tobj.t;
            return *this;
        }
        //前自加操作符
        T& operator ++(){
            ++t;
            return *this;
        }
        //后自加操作符
        T operator ++(int){
            T tmp(*this);
            ++ this->t;
            return tmp;
        }
        void print(){
            cout<<"addr:0x"<<hex<<(int)this<<".t="<<t<<endl;
        }
    private:
        int t;
    };
    
    
    int main()
    {
        T t=1;
        //t.print();
        t=2;    //生成一个临时对象 tmp(2),再调用operator =方法,将其值赋给t
        //t.print();
    /*
        cout<<"T 自加之前"<<endl;
        t.print();
        ++t;
        cout<<"T 自加之后"<<endl;
        t.print();
    
        T t2=++t;
        t.print();
        t2.print();
    */
        cout<<"后加操作测试"<<endl;
        T t3= t++;
        t.print();
        t3.print();
    
        cin.get();
        return 0;
    }
    
  • 相关阅读:
    HDU 1698-Just a Hook
    HDU 1394 Minimum Inversion Number(线段树)
    HDU 4253-Two Famous Companies(二分+最小生成树)
    POJ 3279
    POJ 2251 Dungeon Master
    POJ1321 棋盘问题
    Charlie's Change POJ
    Coins —— POJ-1742
    sublime text主要快捷键列表
    根据电脑分辨率调整网站的布局
  • 原文地址:https://www.cnblogs.com/wucg/p/1968909.html
Copyright © 2011-2022 走看看