C++物件導向進階編程(七)point-like classes和function-like classes

來源:互聯網
上載者:User

標籤:簡單實現   侯捷   image   template   eth   編程   進階   輸出   span   

技術在於交流、溝通,轉載請註明出處並保持作品的完整性。

1.pointer-like class 類設計成指標那樣,可以當做指標來用,指標有兩個常用操作符(*和->),所以我們必須重載這兩個操作

    /*簡單實現一下智能指標的*與 -> 操作符*/    template <class T>    class shared_ptr_test {            public:        T& operator* () const //重載*        {            return *px;        }        T* operator->() const //重載 ->        {            return px;        }        shared_ptr_test(T* p):px(p){};    private:        T * px; //指向class的一個指標        long  pn;    };    struct Foo    {    //    ...        void method(void) {};    };    int main()    {        shared_ptr_test<Foo> sp(new Foo);                 Foo f(*sp); //*作用後自動銷毀  
            //使px 指向Foo class sp->method(); //1.->作用後繼續填充
             //2.== f->method(); sp->method() 會轉換成 px->method();即Foo::method() return 0; }

這個時候我們就可以像使用指標那樣使用這個class了

 

2.function-like classes 類可以像函數那樣使用,那我們必須重載 func operator call 即[()] 操作符

template<typename T>class lineFeed{public:    void operator()(const T &x)    {        cout<<x<<endl;    }};int main(){    int tmp[]={1,2,3,4,5};    for_each(tmp,tmp+5,lineFeed<int>());    return 0;}

輸出結果

參照<<侯捷 C++物件導向進階編程>>

 

C++物件導向進階編程(七)point-like classes和function-like classes

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.