首先,定义如下类A:
class A
{
private:
static int val_s;
public:
static int getVal(){cout << "call getVal in A..." << endl;return val_s;}
};
值得注意的是,这样的static成员函数必须满足如下的要求:
1 不能操作非staitc的成员变量
2 不能声明为const , volatile 或者是 virtual。
3 不需要经由类的对象来调用。(虽然使用类的对象来调用也是合法的)。
#include <bits/stdc++.h>
using namespace std;
class A
{
private:
static int val_s;
public:
static int getVal(){cout << "call getVal in A..." << endl;return val_s;}
};
int A::val_s = 4;
int main(void)
{
cout << ((A *)0)->getVal() << endl; //构造一个临时的对象来调用static函数
A a;
cout << a.getVal() << endl; //通过类的对象来访问
cout << A::getVal() << endl; //通过类的作用域来访问
return 0;
}
原文地址:http://blog.csdn.net/xuqingict/article/details/39099697