Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/130.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在C++中的类函数中创建类的实例?_C++_Class_Instance_Simulation - Fatal编程技术网

在C++中的类函数中创建类的实例?

在C++中的类函数中创建类的实例?,c++,class,instance,simulation,C++,Class,Instance,Simulation,我正在尝试创建一个各种各样的有机体模拟,其中一个需要的函数是,每当一个雄性和雌性有机体彼此相邻时,就会创建一个类的新实例。所以我基本上需要这样的东西: class foo { int a; }; void double_foo { //Create new instance of foo //First time its called, foo instance_1; //Second time its called, foo instance_2; //... } void define

我正在尝试创建一个各种各样的有机体模拟,其中一个需要的函数是,每当一个雄性和雌性有机体彼此相邻时,就会创建一个类的新实例。所以我基本上需要这样的东西:

class foo
{
  int a;
};

void double_foo
{
//Create new instance of foo
//First time its called, foo instance_1;
//Second time its called, foo instance_2;
//...
}
void define_foo
{
//instance_1.a = random number
//instance_2.a = random number
...
//instance_n = random number
}

创建新有机体的函数应该如下所示我复制了原始代码的粘贴部分:

class organism//Organism class
{
...
        void org_reproduce(string map[70][70], std::vector<organism>& childs)//If organism of opposite sex exists in a movable to space, make another organism
        {
            if(shouldReproduce)
            {
                organism child;
                // initialize as desired
                child.sex = rand(...) // randomize sex
                child.age = 1;
                child.hunger = ?;
                child.x = this.x;
                child.y = this.y;
                childs.emplace_back(child);
            }

        }//End of func
您需要将其称为“主要”并将该生物体与所有其他生物体一起存储:

int main()
{   //Defining variables
    string map[70][70];
    srand(time(NULL));

    std::vector<organism> allOrganisms;
    // add some initial organisms
    ....

    // loop that gives organisms life
    while(true)
    {
        std::vector<organism> childs;
        for(organism& org : allOrganisms)
        {
            // call all kinds of moving and etc. functions on org
            ...

            // time to reproduce
            org.org_reproduce(map, childs);
        }

        // add all childs to the herd
        allOrganisms.insert(allOrganisms.end(), childs.begin(), childs.end());
    }

    return 0;
}

你说唯一的名字是什么意思?每个实例都有一个名为name的成员,或者name对您来说意味着变量绑定?创建实例同样简单。真正的问题是你将如何处理这个实例。是否将其添加到全局std::数组?从父对象链接它?您必须对新实例执行某些操作,以便它不会泄漏。@RyanBemrose您甚至不需要调用new。这将导致不必要的复杂性。那么问题到底是什么呢?想做就做您可能还想学习一些设计模式,这些模式可能会给您带来好的想法,例如各种工厂模式。事实上,你的问题对于堆栈溢出来说太模糊了……我需要做一个复制函数,这样当一个雄性和雌性有机体在网格上移动时彼此靠近时,它们就会创建一个新的有机体。新的生物被认为和所有其他沿着网格移动的生物一样,寻找食物和配偶。。。这是我到目前为止的代码:它还没有完成,但我想你可以看到我要用它去哪里,因为这正是我需要的!!!非常感谢你!