2016-09-10 8 views
-3

私はソートの生物シミュレーションを作成しようとしています。そして、望む機能の1つは、男性と女性の生物がお互いに隣り合っているときにクラスの新しいインスタンスを作成するものです。だから私は基本的にのようなものが必要になります。C++のクラス関数内からクラスのインスタンスを作成しますか?

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 
} 
+0

ユニークな名前はどういう意味ですか?すべてのインスタンスにnameというメンバーがあります。名前は変数バインディングを意味しますか? – Lasoloz

+0

インスタンスを作成するのは簡単です。本当の疑問は、あなたはそのインスタンスで何をするつもりです。それをグローバル 'std :: array'に追加しますか?それを親オブジェクトからリンクしますか?新しいインスタンスで何かをして漏れないようにする必要があります。 –

+1

@RyanBemrose 'new'を呼び出す必要はありません。それは不必要な複雑さをもたらすでしょう。 – juanchopanza

答えて

1
新生物は(私はあなたの元のコードのコピー・貼り付けパーツました)このようになるはず作成

あなたの機能:

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; 
} 
+0

これはまさに私が必要なものです!どうもありがとうございます! –

関連する問題