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