C + + Programming Method 3: Static members in a class

Source: Internet
Author: User

A data member that is preceded by a static decoration on a type, is subordinate to the class, becomes a static data member of the class, also known as a "class variable"

A static data member is shared by all objects of that class (that is, the data field in all objects is actually in the same memory location)

Static data is assigned an initial value in the implementation file in the following format:

Type Classname::static_var = Value;

The return value type is preceded by the static modifier's member function, which is called a statics member function, and they cannot invoke a non-static member function;

A static member (data, function) of a class can be accessed either through an object or through a class name class;

#include <iostream>using namespacestd;classtest{Static intcount; Public: Test () {count++; } ~test () {count--; } Static intHow_many () {returncount;}};intTest::count =0;voidprint (Test t) {cout<<"Tests:"<< T.how_many () <<Endl;}intMain () {Test T1; cout<<"test#"<< Test::how_many () <<Endl; Test T2=T1; cout<<"test#"<< Test::how_many () <<Endl;    Print (T2); cout<<"test#"<< T1.how_many () <<","<< T2.how_many () <<Endl;
return 0;}

Constant members in a class

Data members that use const adornments, called constant data members of a class, cannot be changed throughout the life of the object;

A const data member can only be set in the initialization list of a constructor, and is not allowed to be set by assignment in the function;

If the member function is modified with const, the member function cannot modify the data member of the class when it is implemented, that is, the statement of the object state cannot be changed in the function body;

If the object is defined as a constant, it can only call a const-decorated member function, and the other member function does not allow invocation;

C + + Programming Method 3: Static members in 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.