C++ static成员函数(转)

原文链接:https://blog.csdn.net/chengqiuming/article/details/89738995

参考链接:

https://blog.csdn.net/weixin_41783335/article/details/92784826

https://blog.csdn.net/qq_38124695/article/details/78188411

https://blog.csdn.net/qq_37375427/article/details/78808900?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task

一 点睛

与静态数据成员不同,静态成员函数的作用不是为了对象之间的沟通,而是为了能处理静态数据成员。

静态成员函数没有this指针。既然它没有指向某一对象,也就无法对一个对象中的非静态成员进行默认访问(即在引用数据时不指定对象名)。

静态成员函数和非静态成员函数的根本区别:非静态成员函数有this指针,而静态成员函数没有this指针。由此决定了静态成员函数不能访问本类中的非静态成员。

静态成员函数可以直接引用本类中的静态数据成员,静态成员函数主要用来访问静态数据成员,而不访问非静态成员。

假如在一个静态成员函数中有如下语句:

cout<<height<<endl;   //若height已声明为static,则引用本类中的静态成员,合法
cout<<width<<endl;    //若width是非静态成员,不合法

但并不是说绝对不能引用本类中的非静态成员,只是不能进行默认访问,因为无法知道去找哪个对象。如果一定要引用本类中的非静态成员,应该加对象名和成员运算符".",如:

cout<<a.width<<endl;   //引用本类对象a的非静态成员

最好养成这样的习惯:只用静态成员函数引用静态数据成员,而不引用非静态数据成员。

二 实战

1 代码

#include<iostream>
using namespace std;
class CStudent{
public:
    CStudent (int n,int s):num(n),score(s){}//定义构造函数
    void total();
    static double average();
private:
    int num;
    int score;
    static int count;
    static int sum;//这两个数据成员是所有对象共享的
};
int CStudent::count=0;//定义静态数据成员
int CStudent::sum=0;
void CStudent::total(){//定义非静态成员函数
    sum+=score; //非静态数据成员函数中可使用静态数据成员、非静态数据成员
    count++;
}
 
double CStudent::average(){//定义静态成员函数
    return sum*1.0/count;//可以直接引用静态数据成员,不用加类名
}
int main(){
    CStudent stu1(1,100);
    stu1.total();//调用对象的非静态成员函数
    CStudent stu2(2,98);
    stu2.total();
    CStudent stu3(3,99);
    stu3.total();
    cout<< CStudent::average()<<endl;//调用类的静态成员函数,输出99
}

2 运行

[root@localhost charpter02]# g++ 0213.cpp -o 0213
[root@localhost charpter02]# ./0213
99

总结:

   

     

原文地址:https://www.cnblogs.com/lh03061238/p/12510744.html