Sasan Ace
Sasan Ace

Reputation: 23

how to overload + operator to add two queues?

I want to add two queues I have defined, what's wrong with my overloading method ? I have tried the exact syntax of operator overloading but it did not work !! These queues are dynamic arrays that we define some operators for them in class of Queue

#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;
    }

    Queue operator + (Queue &q1 , Queue &q2 ) {
        Queue q3 = q1 + q2;
        return q3;
    }
}; 
    

Main:

int main() {
    Queue q1;
    q1.add(42); q1.add(2); q1.add(8);  q1.add(1);
    Queue q2;
    q2.add(3); q2.add(66); q2.add(128);  q2.add(5);
    Queue q3 = q1+q2;
    q3.print();
    return 0;
} 

Upvotes: 0

Views: 710

Answers (2)

I used a for loop to add the queue in simpler code

The operator can be defined in the following way.

friend Queue operator + (const Queue &q1, const Queue &q2)
{
    int i = 0;

    Queue q3;
 
    q3.size = q1.size + q2.size;

    for(i = 0; i<q1.size; i++)
    {
        q3.queue[i]=q1.queue[i];
    }      
    for(int k=0; k<q2.size; k++)
    {
        q3.queue[i]=q2.queue[k];

        i++;
    }    
    return q3;
}

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 310990

The operator can be defined the following way

#include <stdexcept>
#include <algorithm>

//...

class Queue
{
    //...
    friend Queue operator + ( const Queue &q1 , const Queue &q2 ) noexcept( false )
    {
        if ( not ( q1.size + q2.size <= 100 ) ) throw std::out_of_range( "Too big queues" );

        Queue q3;

        std::copy( q1.queue, q1.queue + q1.size, q3.queue );
        std::copy( q2.queue, q2.queue + q2.size, q3.queue + q1.size );

        q3.size = q1.size + q2.size;

        return q3;
    }
};

Pay attention to that you need explicitly to define the destructor and a copy constructor and the copy assignment operator.

Upvotes: 1

Related Questions