#include <iostream>
using namespace std;
class B {
public:
int getC() {
return c;
}
void setC(int _c) {
c = _c;
}
static void getMem() { // 静态成员函数是属于类
//cout << a << endl; // 编译error 非静态成员变量,无法在静态成员函数使用
cout << c << endl;
}
protected:
private:
int a;
int b;
static int c; // 静态成员变量
};
int B::c = 0;
// static修饰的变量是属于类,所有的对象都能公用
void main01() {
B b1;
B b2;
cout << b2.getC() << endl;
b1.setC(100);
cout << b2.getC() << endl;
system("pause");
}
void main() {
// 调用静态成员函数的方法一
B::getMem();
// 调用静态数据成员函数方法二
B bb1;
bb1.getMem();
system("pause");
}
C++ static关键字
最新推荐文章于 2025-12-10 21:25:44 发布
本文详细介绍了C++中静态成员的使用方法,包括静态成员变量和静态成员函数的特点及应用场景。通过实例展示了如何定义和使用静态成员,并解释了静态成员与普通成员之间的区别。
860

被折叠的 条评论
为什么被折叠?



