Static member function

Static member function

Static member function can directly access static data and function members of the class. To access non-static member must pass objects.

Example:

class A{
public:
  static void f(A,a);
private:
  int x;
};
void A::f(A,a){
  cout<<x;   //对x的引用是错误的
  cout<<a.x;  //正确
}

Specific Case Study:

#include "pch.h"
#include <iostream>
using namespace std;

class point {     //Point 类定义
public:           // 外部接口
    point(int x = 0, int y = 0) :x(x), y(y) { //构造函数
        //在构造函数中对count累加,所有对象共同维护同一个count
        count++;
    }
    point(point &p) {   //复制构造函数
        x = p.x;
        y = p.y;
    }
    ~point() { count--; }
    int getx() { return x; }
    int gety() { return y; }
    static void showcount() {  //静态函数成员
        cout << "obiect count=" << count << endl;
    }
private:      //私有数据成员
    int x, y;
    static int count;    //静态数据成员声明,用于记录点的个数
};

int point::count = 0;   //静态数据成员定义和初始化,实用类名限定

int main() {
    point a(4, 5);    //定义对象a,其构造函数会使count增1
    cout << "point a:" << a.getx() << "," << a.gety() << endl;
    point::showcount();  //输出对象个数
     
    point b(a);    //定义对象b,其构造函数会使count增1
    cout << "point b:" << b.getx() << "," << b.gety() << endl;
    point::showcount();  //输出对象个数
    return 0;
}

Compile the results:

Summary: The benefits of using a static member function is not dependent on any object, direct access to static data.

Guess you like

Origin www.cnblogs.com/nanmao/p/11599247.html