Static member of the class

Source: Internet
Author: User

Sometimes a class requires some of its members to be directly related to the class itself, rather than being associated with each object of the class.

Declare static members

We add the keyword static before the declaration to associate the member with the class. Like other members, static members can make the members public or private.The types of static data members can be constants, references, pointers, class types, etc..

For example, we define a class that represents a bank's account record:

class Account{public:    void calculate() {amount+=amount*interestRate;}    static double rate() {return interestRate;}    static void rate(double);private:    std::string owner;    double amount;    static double interestRate;    static double initRate();};

The static member of the class exists outside any object, and the object does not contain any data related to the static data member. Therefore, each account object contains two data members: Owner and amount. Only one interestrate object exists and it is shared by all account objects.

Similarly, static member functions are not bound to any object,They do not contain the this pointer.. As a result,Static member functions cannot be declared as const, and we cannot use this pointer in the static function.This restriction applies to both explicit use of this and implicit use of non-static members. Static member functions cannot call non-static members of a class. Because the static member function does not include the this pointer. Static member functions cannot be declared as virtual, const, and volatile functions at the same time.

Class base {virtual static void func1 (); // error static void func2 () const; // error static void func3 () volatile; // error };

 

Use static members of a class


We use the scope operator to directly access static members:

Double R;

R = Account: Rate (); // use the scope operator to access static members

Although static members do not belong to an object of the class, we can still use the class object, reference, or pointer class to access static members:

Account AC1;

Account * ac2 = & AC1;

// Call the equivalent form of the static member function rate

R = ac1.rate (); // use the account object or reference

R = ac2-> rate (); // pointer to the account object

A member function can directly use a static member without using the scope operator.

Class account {

Public:

Void calculate () {amount + = Amount * interestrate ;}

PRIVATE:

Static double interestrate;

};

 

Static data member functions

Static member functions: static member functions can only access static member variables. to access non-static member variables, you can only access non-static member variables and static member functions of an object. You can pass a pointer to an object and reference other parameters to this static member function.

 class   a   {  public:      a():m_ia(123)   {}      int   getia()   {   return   m_ia;   }      static   int   f(a &aa)   {   return   aa.getia();   }  private:      int   m_ia;  };  void   main()  {      a   aa;      cout<<a::f(aa);  }  

Static member functions cannot call non-static members, including non-static member functions and non-static member variables. Can static member functions be called in non-static member functions? The answer is yes, because static member functions belong to the class itself and exist before class objects are generated, so static member functions can be called in non-static member functions. In fact, we can also consider it from the perspective of a memory model. That is to say, no matter what operations we take, the program code runs in the memory and only occupies a place in the memory, we can access it. If a member function or member variable is not generated in the memory, the result cannot be accessed. All static member functions can only access static member variables.

Function members declared using the static keyword are static, and static member functions also belong to the entire class. They are shared by all objects of the same class.
As a member function, its access attributes can be strictly controlled by classes. For public static function member functions, they can be called by class names or object names, however, we recommend that you use an object name to reference static function members. note: Generally, member functions can only be called by object names.
A static member function of a class has only one copy, so it is restricted in accessing object data and functions. the static member function can directly access the static data members of the class. for access to non-static data members, the object name must be obtained by passing parameters, and then accessed by the object name. it can be seen that it is quite troublesome to access non-static members through static function members. Generally, it is mainly used to access global variables or static data members in the same class, it is especially used with the latter to maintain the data shared between objects in the same class.
Constructor and destructor cannot be defined as static. The constructor should give each object a this pointer. If it can be static, how can it construct and access this pointer?
Obviously not!

Static member variables are generally defined in the. cpp file:

Double account: _ interestrate = 0.0589;

In addition to adding the keyword static before the function declaration in the class body and cannot be declared as const or volatile, the declaration of static member functions is the same as that of non-static member functions, the keyword static cannot be specified for function definitions that appear in external classes.

Const string STR = "liangxueliang ";
Account * ACC = new account (222222, STR );
ACC-> getrate ();
Account: getrate ();

 

Define static data members

Like other member functions, we can define static member functions both inside the class and outside the class. When a static member is defined outside the class, the static keyword cannot be repeated. This keyword only appears in the declaration statement inside the class:

Void account: Rate (double newrate)

{
Interestrate = newrate;

}

Like all members of a class, when we point to a static member outside the class, we must specify the Class Name of the member. The static keyword appears only in the declaration statement inside the class..

Because static data members do not belong to any object of the class, they are not defined when the class object is created. This means they are not initialized by the class constructor. In general, We Cannot initialize static data members within the class. On the contrary, each static member must be defined and initialized outside the class. Like other objects, a static data member can be defined only once.

Similar to a global variable, a static data member is defined outside any function. Therefore, once defined, it will remain in the entire life cycle of the program.

The method for defining static data members is similar to that for defining member functions outside the class. We need to specify the object type name, and then the class name, scope operator, and member's own name:

// Define and initialize a static member

Double account: interestrate = initrate ();

This statement defines an object named interestrate, which is a static member of the account class and its type is double. Starting from the class name, the rest of the Definition Statement is within the scope of the class. Therefore, we can directly use the initrate function. Note that although the initrate is private, we can use it to initialize interestrate. Like other Member definitions, interestrate can also be a private member of the category.

To ensure that the object is defined only once, the best way is to put the definition of static data members and the definition of other non-inline functions in the same file.

 

Class initialization of static members

Generally, static members of a class should not be initialized within the class. However, we can provide static members with an internal class initial value of the const Integer type. However, static members must be constexpr of the nominal value type. The initial value must be a constant expression. Because these members are constant expressions, they can be used in all places that apply to constant expressions. For example, we can use an initialized static data member to perform the dimensions of several group members:

Class account {public: static double rate () {return interestrate;} static void rate (double); Private: static constexpr int period = 30; double daily_tbl [period]; // period is a constant expression };

If an initial value is provided inside the class, the member definition cannot specify another initial value:

// Definition of a static member without an initial value

Constexpr int account: period; // The initial value is provided in the class definition.

Even if a constant static data member is initialized within the class, the member should be defined outside the class.

 

Static members can be used in some scenarios, while common members cannot

As we can see, static members are independent of any object. Because, in some cases where non-static data members may be illegal, static members can be used normally. For example,Static data members can be incomplete types. In particular, the type of a static data member can be its class type. Non-static data members are restricted and can only be declared as pointers or references to their classes.

Class bar {public ://...... PRIVATE: static bar mem1; // correct: static members can be incomplete bar * MEM2; // correct: pointer members can make incomplete bar mem3; // error: the data member must be of the full type };

Another difference between a static member and a common member is that we can use a static member as the default real parameter:

Class Screen {public: // bkground is not a static member screen & clear (char = bkground); Private: static const char bkground ;};

A non-static data member cannot be used as a default real parameter because its value is a part of the object. In this case, an object cannot be actually provided to obtain the value of the member from it, leading to an error.

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.