什么时候用static成员
/*
什么时候使用静态成员? 当需要多个对象公用某个成员时
什么时候使用静态成员函数? 需要不生成对象就取访问静态成员时
//静态成员的会在构造函数前完成初始化,在构造函数里再初始化一次会覆盖掉原来的值。
使用静态成员函数的好处:
1、如果需要把某个成员函数作为钩子注册给别人使用,又不想把this指针传过去,就使用静态成员函数
*/
class IfStatic { public: IfStatic() { //room = 0; //静态成员的会在构造函数前完成初始化,这里在构造函数里再初始化一次会覆盖掉原来的值。 age = 0; } ~IfStatic() {} void setRoom(int n) { room = n; } void setAge(int m) { age = m; } int age; static int room; }; int IfStatic::room = 10; int main() { IfStatic xiaoming; xiaoming.setAge(8); xiaoming.setRoom(11); cout << xiaoming.age << endl; // 8 cout << xiaoming.room << endl; // 11 IfStatic xiaohong; cout << xiaohong.age << endl; // 0 cout << xiaohong.room << endl; // 和小明共用一个room 11 xiaohong.setAge(7); xiaohong.setRoom(9); cout << xiaoming.age << endl; // 8 cout << xiaoming.room << endl; // 9 cout << xiaohong.age << endl; // 7 cout << xiaohong.room << endl; // 和小红共用一个room 9 return 0; }

浙公网安备 33010602011771号