静态成员函数怎么引用对象
静态数据成员 (Static data member )
A static data member is also known as "Class Member" and it is available for all classes. In other words – we can say "A static data member is just like a global variable for a class". Generally, static data members are used to maintain the common things related to the class, like counting the objects etc.
静态数据成员也称为“类成员” ,并且可用于所有类。 换句话说,我们可以说“静态数据成员就像类的全局变量一样”。 通常, 静态数据成员用于维护与类相关的常见事物,例如对对象进行计数等。
静态成员函数 (Static Member Function)
A static member function is used to access or manipulate the static data member, other data member cannot be used with a static member function.
静态成员函数用于访问或操作静态数据成员,其他数据成员不能与静态成员函数一起使用。
Program:
程序:
This program is implemented to count the total number of created objects with the help of static data member and static member function.
该程序的实现是借助静态数据成员和静态成员函数对创建的对象总数进行计数。
A static data member needs to be declared first that we declared in private section: Example: static int count;
首先需要声明一个静态数据成员,然后在私有部分中声明它:示例: static int count;
To count the object, data member count must be incremented by 1, that we have done in the constructor because the constructor is invoked when a new object is created.
要对对象计数,数据成员计数必须增加1,这在构造函数中已经完成,因为在创建新对象时会调用构造函数。
To print the total number of created objects, we created a static member function named totalObjects() which is returning the value of count.
要打印已创建对象的总数,我们创建了一个名为totalObjects()的静态成员函数,该函数返回count的值。
Final and important thing – A static data member must be initialized outside of the class with the class name. Example: int Message::count =0;
最后一件重要的事情–静态数据成员必须在类外部使用类名进行初始化。 示例: int Message :: count = 0;
#include <iostream>
#include <string.h>
using namespace std;
class Message
{
private:
char str[30];
//static data member to count the objects
static int count;
public:
//constructor
Message()
{
count++;
}
//member function to initialise message
void initMessage(char s[])
{
strcpy(str,s);
}
//member function to print message
void printMessage(void)
{
cout << str << endl;
}
//static member function
static int totalObjects(void)
{
return count;
}
};
//initialise static member function
int Message::count =0;
//main function
int main()
{
Message M1;
Message M2;
Message M3;
M1.initMessage("Message one");
M2.initMessage("Message two");
M3.initMessage("Message three");
M1.printMessage();
M2.printMessage();
M3.printMessage();
//printing object count
cout << "Total objects created: " << Message::totalObjects() << endl;
return 0;
}
Output
输出量
Message one
Message two
Message three
Total objects created: 3
翻译自: https://www.includehelp.com/cpp-programs/count-the-created-objects-using-static-member-function.aspx
静态成员函数怎么引用对象