0

Overloading + operator

Hi, having some trouble overloading my + operator to add two arrays together. Keep getting a type error can not convert int to Queue, but I thought I was accessing the int from the class. Ideas? class Queue { int size; int* queue; public: Queue() { size = 0; queue = new int[100]; } I add some other functions then write: Queue operator+ (Queue obj1){ Queue sum; *(sum.queue) = *(sum.queue)+ *(obj1.queue); return *sum.queue; } Then after declaring q1 and q2 in main: Queue q3 = q1+q2;

6th Feb 2023, 3:30 PM
Louise Def
8 Answers
+ 2
Brill! Thanks :)
6th Feb 2023, 4:22 PM
Louise Def
+ 1
Your welcome đŸ€— if I can help gladly :)
6th Feb 2023, 3:52 PM
ArsenicolupinIII
+ 1
Maybe the error you're encountering is because you're trying to assign the value of a pointer (queue) to an integer (*sum.queue). You need to assign each element of the queue array to the corresponding element of the sum.queue array, instead of trying to assign the entire array. try to update this way class Queue { int size; int* queue; public: Queue() { size = 0; queue = new int[100]; } Queue operator+ (Queue obj1){ Queue sum; for (int i = 0; i < size; i++) { sum.queue[i] = queue[i] + obj1.queue[i]; } sum.size = size; return sum; } }; int main() { Queue q1, q2; // populate q1 and q2 Queue q3 = q1 + q2; // use q3 return 0; }
6th Feb 2023, 4:11 PM
ArsenicolupinIII
+ 1
đŸ€—đŸ€—đŸ€—
6th Feb 2023, 4:28 PM
ArsenicolupinIII
0
The error you're encountering is because you're trying to return an int (the first element of the array) instead of the Queue object. You should return the entire sum object. Also, when adding the arrays together, you need to loop through both arrays and add the corresponding elements of each array to the corresponding element in the sum array. Here's an updated implementation: class Queue { int size; int* queue; public: Queue() { size = 0; queue = new int[100]; } Queue operator+ (Queue obj1){ Queue sum; for (int i = 0; i < size; i++) { sum.queue[i] = queue[i] + obj1.queue[i]; } sum.size = size; return sum; } }; int main() { Queue q1, q2; // populate q1 and q2 Queue q3 = q1 + q2; // use q3 return 0; } I hope I have been of some help
6th Feb 2023, 3:38 PM
ArsenicolupinIII
0
That’s brill! Thanks!
6th Feb 2023, 3:51 PM
Louise Def
0
:D
6th Feb 2023, 3:52 PM
Louise Def
0
Hm
 currently getting an ‘invalid conversion from int* to int error

6th Feb 2023, 4:02 PM
Louise Def