How do I define Operator= for a c++ struct?

Asked

Viewed 75 times

1

I have the structure to follow:

struct PATH {

  vector<ARCO_TEMPO> rota;
  set<int> rotaAux;
  float COST;
  int nArcosVoyage;
  vector<bool> VisitedNodes;
  vector<vector<bool>> VisitedVertices;
  int head_no;
  int head_time;
  int tail_no;
  int tail_time;
  float reducedCost;
  float duracao;
  int auxNumAircrafts;

};

How do I create Operator = for this structure? I thought I could do it this way:

PATH& PATH::operator=(const PATH& p1) {

  COST = p1.COST - cFixo[aa]*p1.auxNumAircrafts;
  reducedCost = p1.reducedCost - cFixo[aa]*p1.auxNumAircrafts;
  auxNumAircrafts = p1.auxNumAircrafts;

  nArcosVoyage = p1.nArcosVoyage;
  head_no = p1.head_no;
  head_time = p1.head_time;
  tail_no = p1.tail_no;
  tail_time = p1.tail_time;
  duracao = p1.duracao;

  for (int i = 0; i < p1.rota.size(); i++) {
    rota[i].a.i = p1.rota[i].a.i; 
    rota[i].a.j = p1.rota[i].a.j; 
    rota[i].slotTimeU = p1.rota[i].slotTimeU; 
    rota[i].slotTimeV = p1.rota[i].slotTimeV; 
  }

  for (int i = 0; i < n; i++) {
    VisitedNodes[i] = p1.VisitedNodes[i];
  }

  for (int i = 0; i < n; i++) {
    for (int j = 1; j <= max_slot; j++) {
        VisitedVertices[i][j] = p1.VisitedVertices[i][j];
    }
  }

  rotaAux = p1.rotaAux;

  return *this;

};

However, the following error appears:

error: Definition of implicitly-declared ːPATH& PATH::Operator=(const PATH&)' PATH& PATH::Operator=(const PATH& P1);

How can I fix this?

2 answers

3

You must declare the method in the class or struct if you want to implement it. Include

PATH& operator=(const PATH& p1);

within the struct statement, along with the member variables.

  • Thanks for the answer. That worked. However, I realized I need a variable that is not global in the Operator= (max_slot) definition. I thought I could just change the function’s header so that: PATH& Operator=(const PATH& P1, int max_slot); But when I do so, the error appears: error: tei PATH& PATH::Operator=(const PATH&, int)' must take Exactly one argument PATH& Operator=(const PATH & P1, int max_slot); ?

  • 2

    No, an assignment always accepts only one argument. You would have to create a function with name (other than Operator) to accept two arguments.

2

If you just want to copy the values without doing anything else, and assuming , you can just do

PATH &operator=(const PATH &) = default;

inside the struct, without needing to define a body. No , you must declare and define the copy constructor manually, as in reply from @epx.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.