0

i am trying to add an integer to the whole array of a class by operator overloading, but i am not sure how can i handle the integer.

void Data::operator +(const Data &c) const
{
    for (int i = 0; i < c.size; i++)
    {
        c.integers[i]=c.integers[i]+   // how do i add the integer with every element of the array?
    }
}

i am trying to get this to work.

data = data + 5;

Integers is an array which i have defined in data class.

khan
  • 9
  • 4
  • `operator+` should not modify the object. You want `+=` for that. To make `data = data + 5;` work, you cannot return `void` from `operator+`. You have to create a `Data`, add to and and return it. Here is an excellent question and answer on how to do operator overloads with minimum surprises for you and other users of your classes: [What are the basic rules and idioms for operator overloading?](https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading) – user4581301 Oct 28 '17 at 04:39
  • i did go through it but i am unable to understand how to do that – khan Oct 28 '17 at 04:50
  • @khan, read the section with the heading **Binary arithmetic operators** of [the first answer](https://stackoverflow.com/a/4421719/434551) to the above post. – R Sahu Oct 28 '17 at 04:59
  • @RSahu how do i add the constant value there ? like in this case data=data+5. how do i add 5 in += function? – khan Oct 28 '17 at 05:08
  • @khan, you overload the operator `+=` using the following interface: `Data& operator+=(int n)`. In the implementation, add `n` to each element of the array. – R Sahu Oct 28 '17 at 05:19
  • @RSahu and what would i return in this +=, and what should i pass in + function? – khan Oct 28 '17 at 05:53
  • @khan, if you don't follow the answer in the post marked as duplicate, answering your specific questions won't help you in the long run. You will be better of picking up a good text book and working through the examples. Here's a [starting point](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – R Sahu Oct 28 '17 at 06:13

0 Answers0