📜  使用静态成员函数计算对象数

📅  最后修改于: 2021-05-25 21:21:23             🧑  作者: Mango

先决条件:静态变量,静态函数
编写一个程序来设计一个类,该类具有名为showcount()的静态成员函数,该函数具有显示该类创建的对象数的属性。

说明:
在此程序中,我们仅说明静态成员函数的方法。我们可以使用static关键字将类成员和成员函数定义为static。在了解静态成员函数之前,我们必须了解静态成员。当我们将一个类的成员声明为静态成员,这意味着无论创建了多少个该类的对象,静态成员只有一个副本

有关静态的要点:

  • 该类的所有对象共享一个静态成员,如果没有其他初始化,则在创建第一个对象时,所有静态数据都将初始化为零。
  • 静态成员函数只能从类外部访问静态数据成员,其他静态成员函数和任何其他函数。
  • 通过将函数成员声明为静态成员,我们使其独立于类的任何特定对象。即使不存在该类的对象,并且仅使用类名和作用域解析运算符::访问静态函数,也可以调用静态成员函数。
  • 我们不能将其放在类定义中,但是可以像下面的示例中那样在类外部进行初始化,方法是使用范围解析运算符::来重新声明静态变量,以使用它来确定它属于哪个类。

例子:

Input : Here  we are not asking for input from the user
Output :count:2
count:3
object number :1
object number :2
object number :3

Input :Here we are not asking for input from the user
Output :count:2
count:3
object number :1
object number :2
object number :3
// C++ program to Count the number of objects
// using the Static member function
#include 
using namespace std;
class test {
    int objNo;
    static int objCnt;
  
public:
    test()
    {
    objNo = ++objCnt;
    }
    ~test()
    {
    --objCnt;
    }
    void printObjNumber(void)
    {
        cout << "object number :" << objNo << "\n";
    }
    static void printObjCount(void)
    {
        cout << "count:" << objCnt<< "\n";
    }
};
int test::objCnt;
int main()
{
    test t1, t2;
    test::printObjCount();
  
    test t3;
    test::printObjCount();
  
    t1.printObjNumber(); 
    t2.printObjNumber(); 
    t3.printObjNumber();
    return 0;
}

输出:

count:2
count:3
object number :1
object number :2
object number :3
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”