简体   繁体   中英

Initializing another class inside class c++

I am trying to make a new Node class and set its coordinates in my class called Colony (my run function is inside of the Colony class). It is segfaulting though. I have tried using new but it isn't working. What should be the fix here? Heres a snippet of the code:

class Node {
public:
  std::vector<double> coords;
  vector<Node> parent;
  vector<Node> childList;
  vector<Attract> closestAtts;
};

class Colony {
public:
  double D, dk, di;
  vector<Attract> attlist;
  vector<Node> nodelist;
  std::vector<vector<double> > attractors;
  std::vector<vector<double> > centroids;

void run() {
// Initializes a colony with starting point
    Node start; 
    start.coords[0] = 100.0; 
    start.coords[1] = 100.0; 
    start.coords[2] = 100.0; 
    nodelist.push_back(start);
}

In your run() method, you are trying to assign the 0th, 1st and 2nd elements of the start.coords vector, but these have not yet been assigned. Instead you should .push_back these values, like so:

void run() {
// Initializes a colony with starting point
    Node start; 
    start.coords.push_back(100.0); 
    start.coords.push_back(100.0); 
    start.coords.push_back(100.0); 
    nodelist.push_back(start);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM