一、上节课没有随时可以获得当前对象的数目(必须有对象且调用getCount()函数)
解决方案一:
将count设置为public,用类名来访问,但是安全性不能得到保证,即使没有对象(提供直接修改count的值)打印的值可能也不为0
解决方案2:
类的静态成员函数
1.静态成员函数是类中的特殊的成员函数
2.静态成员函数隶属于整个类所有
3.可以通过类名直接访问公有的静态成员函数
4.可以通过对象名访问公有的静态成员函数
#include <iostream>
using namespace std;
class Demo
{
private:
int i;
public:
int getI();
static void StaticFunc(const char* s);
static void StaticSetI(Demo& d, int v);
};
int Demo::getI()
{
return i;
}
void Demo::StaticFunc(const char* s)
{
cout << "StaticFunc: " << s << endl;
}
void Demo::StaticSetI(Demo& d, int v)
{
d.i = v;
}
int main()
{
Demo::StaticFunc("main Begin...");//通过类名直接访问
Demo d;
Demo::StaticSetI(d, 10);
cout << "d.i = " << d.getI() << endl;
Demo::StaticFunc("main End...");
return 0;
}
静态成员函数不可以直接访问普通的成员变量,但可以通过类名或者对象名来访问
静态成员函数 普通成员函数
所有对象共享 yes yes
隐含的this指针 no yes
访问普通成员变量(函数) no yes
访问静态成员变量(函数) yes yes
通过类名直接访问 yes no
通过对象名直接访问 yes yes
在调用普通的成员函数时,有一个隐含的this指针指向当前对象,但是静态成员函数不与具体的对象绑定,故它没有this指针,也不能调用普通的成员函数(变量)
最终解决方案:
#include <iostream>
using namespace std;
class Test
{
private:
static int cCount;
public:
Test()
{
cCount++;
}
~Test()
{
--cCount;
}
static int GetCount()
{
return cCount;
}
};
int Test::cCount = 0;
int main()
{
cout<<"count = " << Test::GetCount()<<endl;//一个对象都没有的时候也可以知道数量
Test t1;
Test t2;
cout<<"count = "<<t1.GetCount()<<endl;
cout<<"count = "<<t2.GetCount()<<endl;
Test* pt = new Test();
cout<<"count = "<<pt->GetCount()<<endl;
delete pt;
cout<<"count = " << Test::GetCount()<<endl;
return 0;
}
小结:
1.静态成员函数是类中的特殊成员函数
2.静态成员函数没有隐藏的this参数
3.静态成员函数可以通过类名直接访问
4.静态成员函数只能直接访问静态成员变量(函数)