Home > Net >  C Overloading the plus operator to add an element to an object
C Overloading the plus operator to add an element to an object

Time:11-11

Constructor for object

Set<T>::Set() {
    buckets = new forward_list<T>[9];
    numBuck = 9;
    numElem = 0;
    maxLoad = 9;
}

Overloading of plus operator

Set<T>::operator (T elem){
    Set<T> res;
    return res;

I don't quite know where to begin with this. This overloaded operator add its parameter elem to a copy of *this and return the result. ex:

Set<char>setA;
Set<char>setB;

setA.Add('a')
setA.Add('b')
setA.Add('c')
// setA contains {'a','b','c'}
setB = setA   'd'
// setB should now contain {'a','b','c','d'}

Any guidance?

edit: Clarified operator overload functionality

CodePudding user response:

For the copy of *this, you can modify the definition of res to use the default copy constructor.

Set<T> res(*this);

Adding the elem argument uses the same method you used for adding elements to setA.

res.Add(elem);

CodePudding user response:

You can just make a copy function in the set, and use the Add function inside the overload. Demo code:

Set<T>::operator (T elem)
{
    Set<T> result;
    result.Copy(*this);
    result.Add(elem);
    return result;
}

NOTE: Or you can follow @jxh's answer and use the default copy constructor. I would make a Copy function just to be explicit. :)

  • Related