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;
8 ответов
+ 2
Brill! Thanks :)
+ 1
Your welcome 🤗 if I can help gladly :)
+ 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;
}
+ 1
🤗🤗🤗
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
0
That’s brill! Thanks!
0
:D
0
Hm… currently getting an ‘invalid conversion from int* to int error…