如何在c ++中为类创建确切数量的对象 [英] How to create exact number of objects for a class in c++

查看:49
本文介绍了如何在c ++中为类创建确切数量的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我必须用c ++创建确切数量的对象

Ex:

Hi
I have to create exact number of objects in c++
Ex:

class Test
{
public:
Test()
{

}
}
int main()
{
 Test t1,t2,t3;
 // if i will create 4th object then it has to throw the exeception.
}

推荐答案

创建一个静态计数器,并在Text类构造函数中递增它。

如果它会达到四,抛出异常。
Create a static counter, and increment it in the Text class constructor.
If it reaches four, throw your exception.


#include<iostream>

using namespace std;
class Test
{
    static int count;
public:
    Test()
    {
        count++;
        if(count==4)
        {
            throw int();
        }
        cout<<count<<endl;
    }
};

int Test::count=0;
int main(int argc, char *argv[])
{
    try
    {
        for(int i=0;i<10;i++)
        {
            Test *t1=new Test[i];
        }
    }
    catch(int)
    {
        cout<<"in catch block";
    }

    return 0;
}


这篇关于如何在c ++中为类创建确切数量的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆