静态成员

由关键字static修饰说明的类成员,称为静态类成员(static class member)。虽然使用static修饰说明,但与函数中的静态变量有明显差异。类的静态成员为其所有对象共享,不管有多少对象,静态成员只有一份存于公用的内存中。

静态成员又分为静态成员函数,静态成员数据

静态数据

#include<iostream>
using namespace std;

class Test
{
    friend void fun(Test &t);
public:
    Test(int d=0)
    {
        count++;
        data = d;
    }
    ~Test()
    {
        count--;
    }
private:
    int data;
    static int count;
};

int Test::count = 0;

void fun(Test &t)
{
    cout << "t.data = " << t.data << endl;
    cout << "Object count = " << Test::count << endl;
}

int main()
{
    Test t1(100);
    Test t2(200);
    fun(t1);
}
View Code

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-02
  • 2021-07-06
  • 2021-07-19
  • 2021-10-26
  • 2021-06-02
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-08-02
  • 2022-12-23
  • 2021-10-07
  • 2021-10-24
  • 2021-07-12
相关资源
相似解决方案