C++static静态成员函数

C++static静态成员函数

静态成员函数

  静态成员函数和静态数据成员一样,它们都属于类的静态成员,它们都不是对象成员。因此,对静态成员的引用不需要用对象名。

  在静态成员函数的实现中不能直接引用类中说明的非静态成员,可以引用类中说明的静态成员。如果静态成员函数中要引用非静态成员时,可通过对象来引用。下面通过例子来说明这一点。

#include 
class M
{
public:
M(int a) { A=a; B+=a;}
static void f1(M m);
private:
int A;
static int B;
};

void M::f1(M m)
{
cout<<"A="<<m.a<<endl;
 cout<<"B="<<b<<endl;
 }

int M::B=0;
void main()
{
M P(5),Q(10);
M::f1(P); file://调用时不用对象名
M::f1(Q);
}
posted @ 2017-06-06 22:21  菜鸡一枚  阅读(172)  评论(0)    收藏  举报