【发布时间】:2018-11-18 00:45:59
【问题描述】:
如何在一个类中声明一个变量来跟踪创建的对象的数量? 示例对象 obj; obj.object_count();
【问题讨论】:
-
类中有一个静态变量,并在构造函数中递增。
-
为什么要同时使用 Java 和 C++ 进行标记?
标签: c++
如何在一个类中声明一个变量来跟踪创建的对象的数量? 示例对象 obj; obj.object_count();
【问题讨论】:
标签: c++
您可以使用static 类成员存储对象计数。并在类构造函数中增加其值,在析构函数中减少其值。
请查找 cmets inline:
#include <iostream>
#include <atomic>
class Object
{
public:
Object() // Constructor
{
// initialize the object
// ...
m_objCount++; // Increase object count when creating object (In constructor)
}
Object(const Object& obj) // Copy constructor
{
m_objCount++;
}
Object(Object&&) // Move constructor
{
m_objCount++;
}
~Object()
{
m_objCount--; // Decrease object count when destroying object
}
static int object_count() // Define a static member function to retrive the count
{
return m_objCount;
}
private:
static std::atomic_int m_objCount; // Use static member to store object count,
// use std::atomic_int to make sure it is thread safe
};
std::atomic_int Object::m_objCount; // Initialize static member
int main()
{
Object obj;
// prints "obj count: 1"
std::cout << "obj count: " << obj.object_count() << std::endl; // call object_count() with object
std::cout << "obj count: " << Object::object_count() << std::endl; // call object_count() with class name
}
【讨论】:
object_count()是static,你可以使用类类型而不是对象变量来调用它:fprintf(stdout, "obj count: %d\n", Object::object_count());为什么你在C++中使用fprintf()而不是使用std::cout ? std::cout << "obj count: " << Object::object_count() << std:::endl;