31 lines
560 B
C++
31 lines
560 B
C++
// 静态成员函数, 内部只能访问静态成员变量
|
|
#include <iostream>
|
|
#include <cstring>
|
|
#include <cstdlib>
|
|
|
|
using namespace std;
|
|
|
|
class A
|
|
{
|
|
public:
|
|
int m;
|
|
static int x;
|
|
static void add(int n)
|
|
{
|
|
// m = 10; // error, 静态成员函数不能访问非静态成员
|
|
x += n;
|
|
cout << "static x = " << x << endl;
|
|
}
|
|
};
|
|
|
|
int A::x = 20; // 静态变量的初始化
|
|
|
|
int main()
|
|
{
|
|
A a1;
|
|
A::add(10); // static x = 30
|
|
cout << "a1.x = " << a1.x << endl; // a1.x = 30
|
|
|
|
return 0;
|
|
}
|