在上一篇文章中,我们讨论了C ++中的静态数据成员,并讨论了可以通过成员函数访问静态数据成员,但是该函数应该是静态成员函数
静态成员函数是一种特殊的成员函数,仅用于访问静态数据成员,其他任何常规数据成员均无法通过静态成员函数访问。就像静态数据成员一样,静态成员函数也是类函数。它不与任何类对象关联。
通过使用以下语法,我们可以使用类名称访问静态成员函数:class_name:: function_name(perameter);
考虑示例:#include
using namespace std;
class Demo
{
private:
//静态数据成员
static int X;
static int Y;
public:
//静态成员函数
static void Print()
{
cout <
cout <
}
};
//静态数据成员 initializations
int Demo :: X =10;
int Demo :: Y =20;
int main(){
Demo OB;
//使用对象名称访问类名称
cout<
OB.Print();
//用类名访问类名
cout<
Demo::Print();
return 0;
}
输出结果Printing through object name:
Value of X: 10
Value of Y: 20
Printing through class name:
Value of X: 10
Value of Y: 20
在上面的程序中,X和Y是两个静态数据成员,并且print()是一个静态成员函数。根据C ++中的static规则,只有static成员函数才能访问static数据成员。不能通过静态成员函数访问非静态数据成员。
注意:内联函数永远不能是静态的。