qfedu-cpp-level/day4/d1.cpp

26 lines
519 B
C++
Raw Normal View History

// 类的静态成员变量的声明、初始化与访问
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
class A
{
public:
static int x;
};
int A::x = 20; // 静态变量初始化,静态成员变量初始化时不需要 static
int main()
{
A a1, a2;
// 访问类的静态成员: 1) A::x, 2) 对象名.x
cout << "A::x = " << A::x << endl; // 20
A::x = 30;
cout << "a1.x = " << a1.x << endl; // 30
cout << "a2.x = " << a2.x << endl; // 30
return 0;
}