当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


C++ Static member用法及代码示例

在上一篇文章中,我们讨论了 C++ 中的静态数据成员,我们讨论了静态数据成员可以通过成员函数访问,但该函数应该是静态成员函数

静态成员函数是一种特殊的成员函数,它只用于访问静态数据成员,不能通过静态成员函数访问任何其他普通数据成员。就像静态数据成员一样,静态成员函数也是一个类函数;它不与任何类对象相关联。

我们可以使用以下语法访问具有类名的静态成员函数:

	class_name::function_name(perameter);

考虑这个例子:

#include <iostream>

using namespace std;

class Demo
{
    private:	
        //static data members
        static int X;
        static int Y;

    public:
    //static member function
    static void  Print()
    {
        cout <<"Value of X:" << X << endl;
        cout <<"Value of Y:" << Y << endl;
    }
};

//static data members initializations
int Demo::X =10;
int Demo::Y =20;


int main()
{
    Demo OB;
    //accessing class name with object name
    cout<<"Printing through object name:"<<endl;
    OB.Print();
    
    //accessing class name with class name
    cout<<"Printing through class name:"<<endl;
    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

在上面的程序中XY是两个静态数据成员和print()是一个静态成员函数。根据C++中的静态规则,只有静态成员函数才能访问静态数据成员。非静态数据成员永远不能通过静态成员函数访问。

注意:内联函数永远不能是静态的。



相关用法


注:本文由纯净天空筛选整理自 Static member function in C++。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。