Application of C + + static members

Source: Internet
Author: User

    1. You cannot reuse the static keyword when you define it outside of a class
    2. The static member function does not contain the this pointer (whether it is displayed or implicitly used)
    3. Static members can be accessed through class objects or through classes
    4. Static members are not initialized by constructors, and static members are generally not initialized inside a class
    5. Static data members are defined outside of any function and can only be defined once
    6. When a static data member is defined, the static data member can be accessed through the class qualifier, whether the static data member is public, protected, or private, but only when defined
    7. The type of a static data member can be the class type that it belongs to, and a non-static data member can only declare a pointer or reference to the class to which it belongs
  
 
  1. #ifndef MAIN_H_INCLUDED
  2. #define MAIN_H_INCLUDED
  3. #include <iostream>
  4. using namespace std;
  5. class ClassTest
  6. {
  7. public:
  8. static int getValue() ;
  9. private:
  10. static int value /*= 1*/;
  11. };
  12. #endif // MAIN_H_INCLUDED
. cpp Files
  
 
  1. #include "main.h"
  2. /**< 对于静态数据成员一般不能在类内进行初始化 */
  3. /**< 若要在类内进行初始化,则要求静态成员必须是常量表达式 */
  4. int ClassTest::value = 2;//在定义时,尽管value是private类型,依然可以通过类限定符进行访问
  5. int ClassTest::getValue()
  6. {
  7. return value;
  8. }
  9. int main()
  10. {
  11. ClassTest classTest;
  12. cout << classTest.getValue() << endl;
  13. /**< 可以使用类名直接访问静态成员,在类外不能访问private成员 */
  14. //cout << ClassTest::value << endl;/**< 错误,因为value是private */
  15. cout << ClassTest::getValue() << endl;
  16. return 0;
  17. }



From for notes (Wiz)

Application of C + + static members

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.