C++】实现一个类,计算程序中创建出了多少个类对象

我们应该要知道,计数的变量,不能包含在每个对象中,应该是所有对象共享。
如下:只是计数了当前对象的内容,所以不能采用
代码1(定义了普通类型的变量)

class Test
{
public:
 Test() :t_count(0)
 {
  t_count++;
 }
 Test(Test& a)
 {
  t_count++;
 }
 ~Test()
 {
  t_count--;
 }
private:
 int _a;
 int t_count;
};
int main()
{
 Test t1, t2;
  return 0;
}

如果给一个全局变量:可以,但如果全局变量在内部被改,就不安全了
代码2(定义了全局变量)

int t_count = 0;
class Test
{
public:
 Test()
 {
  t_count++;
 }
 Test(Test& a)
 {
  t_count++;
 }
 ~Test()
 {
  t_count--;
 }
private:
 int _a;
};
int main()
{
  Test t1, t2;
  return 0;
}

所以,我们可以在类中定义一个共享的成员变量,它是所有类对象共享的,不属于某个具体的实例,这就需要用到static了,先看代码了解下:
代码3(定义了static成员变量)

class Test
{
public:
 Test() :_a(0)
 {
  t_count++;
 }
 Test(Test& a)
 {
  t_count++;
 }
 ~Test()
 {
  t_count--;
 }
 static int GetCount()//静态成员函数
 {
 return t_count;
 }
 //int GetCount1()//普通成员函数
 //{
 // cout<<this<<endl;
 // return this->_a;
 //}
private:
 int _a;
 static int t_count;//静态成员变量   声明
};
int Test::t_count = 0;//静态成员变量在类外初始化,且不添加static关键字
void testCount()
{
 Test t1, t2;
 cout << Test::GetCount() << endl;
 //cout << t_count << endl;
}
int main()
{
 Test::GetCount();
 Test t1, t2;
 cout << Test::GetCount() << endl;//2
 //cout << t1.GetCount() << endl;//也可以通过对象访问
 testCount();//4
 cout << Test::GetCount() << endl;//2
 system("pause");
 return 0;
}

static成员

概念
声明为static的类成员称为类的静态成员,用static修饰的成员变量,称为静态成员变量用static修饰的成员函数,称为静态成员函数静态的成员变量一定要在类外进行初始化。

特性
1.静态成员为所有类对象所共享,不属于某个具体的实例(所以要在类外初始化)
2.静态成员变量必须在类外定义(初始化),定义时不添加static关键字
3.类静态成员可用类名::静态成员或者对象.静态成员来访问
4.静态成员函数没有隐藏的this指针,不能访问任何非静态成员
5.静态成员和类的普通成员一样,也有public、protected、private3中访问级别

具体代码看上面代码3
在这里插入图片描述
普通类型的成员变量和static成员变量:在这里插入图片描述
普通类型的成员函数和static成员函数:
在这里插入图片描述

发布了73 篇原创文章 · 获赞 2 · 访问量 2859

猜你喜欢

转载自blog.csdn.net/weixin_43219708/article/details/104165585