Static member function

Source: Internet
Author: User

As with static data members, static member functions are shared by all objects, not individually, because static member functions do not pass the this pointer, so static member function can only access static members and cannot access non-static members. But non-static can access static members.

1#include <iostream>2 using namespacestd;3 classx{4     inti;5     Static intJ;6  Public:7XintIi=0): I (ii) {8j = i;//non-static member function can access static member function or data9     }Ten     intVal ()Const{returni;} One     Static intincr () { A         //i++; Error:static member function can not access non-static member data -         return++J; -     } the     Static intf () { -         //!val () error:static member function can not access non-static member function -         returnincr (); -     } +  - }; + intX::j =0; A intMain () { at x x; -x* XP = &x; - x.f (); -Xp->f (); - x::f (); -System"Pause"); in     return 0; -  to}

When an object accesses a static member, it can pass the dot operator and the arrow operator. This connects the static member function to an object, or it can be accessed directly using the Classname::static member Fucntion name.

Sometimes you can set the constructor to private, as in the following example

1 classegg{2     StaticEgg E;3     inti;4Egg (intII): I (ii) {}5Egg (Constegg&);//Prevent copy-construction6  Public:7     Staticegg* instance () {return&e;}8     intVal ()Const{returni;}9 };Ten  OneEgg Egg::e ( -); A intMain () { -     //! Egg x (0); Error can ' t create an Egg -cout << egg::instance ()->val () <<Endl; theSystem"Pause"); -     return 0; -  -}

To not allow the class to copy the created object, a private copy constructor is added

Egg (const egg&);//prevent copy-construction
Such a class would not create objects like the following
Egg e=*egg::instance ();

Static member function

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.