C++统计对象个数

本文展示了一个使用 C++ 中的 auto_ptr 来统计 A 类对象实例数量的例子。通过将构造函数设为私有并利用静态成员变量 i 进行计数,确保了对象的正确跟踪。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

利用auto_ptr统计C++的对象个数,要注意一定要把构造函数声明为私有,代码如下:

 

class A{
private:
    
static int i;
    A(){
    }
    A(
const A&){}
public:
    
static void init(){
        A::i
=0;
    }
    auto_ptr
<A> static makeA(){
        i
++;
        auto_ptr
<A> p(new A);
        
return p;
    }
    
static int getNum(){
        
return A::i;
    }
};
int A::i=0;
int main(){
    
for(int i=0;i<10;i++){
        auto_ptr
<A> p=A::makeA();
    }
    cout
<<A::getNum()<<endl;
}

转载于:https://www.cnblogs.com/CUCmehp/articles/1376379.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值