I am trying to do operator overloading in Queue But there is some error in the code. This is project problem of C++ Queue Manage | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

I am trying to do operator overloading in Queue But there is some error in the code. This is project problem of C++ Queue Manage

#include <iostream> using namespace std; class Queue { int size; int* queue; public: Queue() { size = 0; queue = new int[100]; } void add(int data) { queue[size] = data; size++; } void remove() { if (size == 0) { cout << "Queue is empty"<<endl; return; } else { for (int i = 0; i < size - 1; i++) { queue[i] = queue[i + 1]; } size--; } } void print() { if (size == 0) { cout << "Queue is empty"<<endl; return; } for (int i = 0; i < size; i++) { cout<<queue[i]<<" <- "; } cout << endl; } //your code goes here Queue operator+(Queue q2){ Queue q3; int size=0; for(int i=0;i<4;i++){ q3.queue[size]=this->queue[size]+q2.queue[size]; size++; } return q3; } }; int main() { Queue q1; q1.add(42); q1.add(2); q1.add(8); q1.add(1); q1.print(); Queue q2; q2.add(3); q2.add(66); q2.add(128); q2.add(5); q2.print(); Queue q3 = q1+q2; q3.print(); return 0; }

16th Jul 2021, 12:05 PM
Rgodella
Rgodella - avatar
3 Answers
+ 2
Instead of creating a new varible size , use q3 object size member variable. Queue operator+(Queue q2){ Queue q3; for(int i=0;i<4;i++){ cout<<q2.queue[q3.size]<<endl; q3.queue[q3.size]=this->queue[q3.size]+q2.queue[q3.size]; q3.size++; } return q3; }
16th Jul 2021, 12:23 PM
Abhay
Abhay - avatar
+ 1
Thanku so much Im trying to sort out this problem from last two hours . But i think so there is no need to print this statement : cout<<q2.queue[q3.size]<<endl;
16th Jul 2021, 12:31 PM
Rgodella
Rgodella - avatar
+ 1
Rgodella ofcourse you don't need to , i was using it to test it and forgot to delete it!
16th Jul 2021, 3:48 PM
Abhay
Abhay - avatar