C + + Object-oriented advanced Programming (vii) Point-like classes and Function-like classes

Source: Internet
Author: User

Technology lies in communication, communication, reproduced please specify the source and maintain the integrity of the work.

The 1.pointer-like class is designed as a pointer and can be used as a pointer with two commonly used operators (* and-), so we have to overload both operations

    /*simple implementation of the * and-operator of the smart pointer*/Template <classT>classshared_ptr_test { Public: T&operator* ()Const //Reload *        {            return*px; } T*operator()Const //Heavy-duty        {            returnpx; } shared_ptr_test (T*p):p x (p) {}; Private: T* PX;//a pointer to class        LongPN;    }; structFoo {//    ...        voidMethodvoid) {};    }; intMain () {shared_ptr_test<Foo> SP (NewFoo); Foo F ((S2);//* Automatic destruction after function
Make PX point to Foo classSP->method ();//1.--- after the action continues to fill
2.== F->method (); Sp->method () will be converted to Px->method (), i.e. Foo::method () return 0; }

At this point, we can use the class as if it were a pointer.

2.function-like classes class can be used like a function, we must overload the Func operator call the [()] operator

Template<typename t>classlinefeed{ Public:    void operator()(ConstT &x) {cout<<x<<Endl; }};intMain () {inttmp[]={1,2,3,4,5}; For_each (tmp,tmp+5,linefeed<int>()); return 0;}

Output results

Reference << Houtie C + + Object-oriented advanced programming >>

C + + Object-oriented advanced Programming (vii) Point-like classes and Function-like classes

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.