Static members of a class

Source: Internet
Author: User

The static members of a class are different from ordinary members, and they have their own characteristics, and I'll take the following classes as an example.


Design bank account class Account#include <iostream> #include <string>class account{private:std::string owner;// Account name double amount;//balance static double interestrate;//interest rate, static data member declaration, this definition is required to initialize the static co when the class external//integer const static data member is declared in the class definition NST int period=30;double Daily_tbl[period];p ublic://constructor Account (const std::string own= "Noname", double amou=0): Owner ( Own), amount (Amou) {}//Note that the constructor cannot initialize static data member//declare deposit date, it is public static data member static std::size_t withdrawdate;//calculated balance Doub Le Applyint () {amount+=amount*interestrate;} Returns the current interest rate static double ()//static member function defined inside class {return interestrate;} Set new interest rate static void setrate (double);//class internally declares a static member function, defined outside the class};d ouble account::interestrate=2.5;// When you define a static data member and initialize it outside of the class, you must use the class action, no longer flag for staticstd::size_t account::withdrawdate=20141222;//to define the deposit date, and initialize the const int period ;//integer const static defined outside the class definition body no longer need to specify an initial value//class external definition setratevoid account::setrate (double newrate) {interestrate=newrate;} int main () {Account act1;//class account instantiates object Act1account *act1ptr=&act1;//class pointer act1ptr points to Act1 object AccouNT &act2=act1;//act2 is a reference to Act1//four ways to call PUBILC static data member withdrawdatesize_t date;date=act1.withdrawdate;// Indirect calls through the object date=act1ptr->withdrawdate;//through pointers date=act2.withdrawdate;//indirectly through Act1 's reference act2 call Date=account:: withdrawdate;//calls directly through the class account//The private static data member can only be called indirectly through the member function double rate;//defines a variable rate, which is used to accept the rates returned by the () function rate= Account::rate ();//Use the class scope operator to call the static member function directly//rate=account::interestrate;//error, cannot directly access the private static data member// Four ways to call the PUBILC static member function rate () Double rate;//to define rates, which are used to accept the return date=act1.rate ();//Indirect call Date=act1ptr->rate () via object;// Call Date=act2.rate () indirectly through pointers,//date=account::rate () indirectly via Act1 reference act2, or directly through the class account}


static data membersTypically, non-static data members exist in every object of the class type, whereas static data members exist independently of any object of the class: each static data member is an object associated with the class and is not associated with the object of the class.
  1. Define--static Keywords

    The static data member must be defined outside the class definition body (only once) and should be initialized at definition time because the static data member is not initialized by the constructor of the class.
    As the interest rate interestrate in the above program, it is defined outside the class definition body as follows:

    Double account :interestrate=2.5;//defines a static data member and initializes it outside the class, you must use the class scope operator (::), which is no longer marked as static

  2. Special integer const static data member

    An integer const static data member must be initialized in the definition body of the class and still need to be defined outside the definition body of the class , without having to specify the initial value.
    As period in the above procedure:

    Class Account

    {

    ...

    Integer conststatic data members are initialized when declared in the class definition

    staticconst int period=30;

    ...

    };

    const int period;//integer const static defined outside the class definition body no longer need to specify an initial value

  3. Call static data member
    1) public static data member
    public static members can be called directly through the scope operator (::), or indirectly by an object, reference, or pointer to an object of that class type.
    As in the above procedure:

    Account act1;//class Account instantiation Object Act1
    account*act1ptr=&act1;//class pointer act1ptr point to Act1 object
    Account&act2=act1;//act2 is a reference to Act1
    Four ways to call PUBILC static data member rate ()
    size_t date;
    Date=act1.rate ();//indirect Call via Object
    Date=act1ptr->rate ();//indirect call via pointer
    Date=act2.rate ();//indirect call via Act1 reference Act2
    Date=account::rate ();//call directly through the class
    account

    We want to know that although static data members can be called indirectly through an object, it belongs to the class and does not belong to the object.
    2)private static data member
    private static data members can only be called indirectly through member functions, and private static is accessible to both static member functions and ordinary member functions.
    The return rate function as described in the above program rates ():

    Double rate;//defines a variable rate that is used to accept the rates returned by the () function
    Rate=rate ();
    Rate=account::rate ();//Here the static member function is called directly with the class scope operator rate (), and rates () return interestrate
    //rate=account:: interestrate;//error, cannot access private static data member directly
  4. The particularity of static data members
    1) The type of a static data member can be the class type of the class to which the member belongs, rather than a static member being qualified to declare a pointer or reference to its own class object

    Class Account
    {
    ...
    Private
    Static account act4;//Correct, the type of the Stactic data member can be the type of its own class
    Account amount;//error, ordinary data member amount cannot be a type of its own class
    Account *act2ptr;//Correct
    ...
    };
    2) static data members can be used as default arguments, and non-static data members cannot

    Window class Screen
    Class screen
    {
    Public
    Clear specific characters on the screen
    screen& Clear (Char=bkground);
    Private
    static const charbkground= ' # ';
    };


Static member functions

number

  1. The
  2. definition--just add the static keyword

    Static member function can be defined inside the class or outside the class. When defined inside a class, with static, when defined outside the class, the declaration inside the class is static, and the definition outside the class does not need to be static, but the class scope operator (::) must be used.
    Rate () as internally defined in the above program:
    Static double rate ()

           {

            return interestrate;

          }
    Externally defined settings new interest rate function setrate ():

    Class Account

    {

    ...

    Public:

    //Set new rate

           static void Setrate (double);//class inside declares a static member function, defined outside the class ...

    };

    //class external definition set new interest rate function Setrate

    void account:: setrate (double newrate)

    {

           interestrate=newrate;

    }

  3. The particularity of a static member function
    1) The  static member function cannot be declared as const

            such as: static void Setrate (double) const;//error

    2)   Static member function cannot be declared as virtual function

    3) static member function does not have this pointer
            This causes the static member function to have no access to the non-static data members, only the static data members, and the normal member functions without this limitation.

            Take the return current rate in the above program as an example:

    class account
    {
               private: Br>           static double interestRate;
    Public:
    / /return current interest rate
    Staticdouble rates ()//static member functions access static data members
           {
                   return interestrate;
          };
    }

  4. Call the static member function
    1) public static member function
    Similar to calling public static data members, there are four ways to call public static members directly through the scope operator (::), or indirectly by invoking a public static member through an object, reference, or pointer to an object of that class type.
    Still take the return current rate function rates () as an example:

    Account act1;//class Account instantiation Object Act1
    account*act1ptr=&act1;//class pointer act1ptr point to Act1 object
    Account&act2=act1;//act2 is a reference to Act1
    Four ways to call PUBILC static member function rate ()
    Double rate;//define rate, which is used to accept return interest rates
    Rate=act1.rate ();//indirect Call via Object
    Rate=act1ptr->rate ();//indirect call via pointer
    Rate=act2.rate ();//indirect call via Act1 reference Act2
    Rate=account::rate ();//call directly through the class account

    2) private static member function

    Such functions are rarely used and are not discussed here.

    The above content is oneself in See "C + + Primer" Some summary, or remove, or oneself add, welcome everybody correct.

Static members of a class

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.