sadboy99
sadboy99

Reputation: 45

how to create an += operator

i have an hpp file that contains a class:

#include <iostream>
#include <iomanip>
#include <cstddef>      // size_t
#include <string>

class Book
{



//private:
    std::string _isbn;
    std::string _title;
    std::string _author;
    double      _price = 0.0;
};

the other class is:


class BookList
{
    
public:
    // Types and Exceptions
    enum class Position {TOP, BOTTOM};

    BookList & operator+=( const BookList & rhs);
    // TO DO
    // concatenates the rhs list to the end of this list

private:
    // Instance Attributes
    std::size_t _capacity; // maximum number of books that can be stored in the dynamic array
    std::size_t _books_array_size;  // number of books in the list
    Book * _bookArray; // the dynamic array of books
};

i have all the functions that i need to do except for the +=operator which needs to concatenate rhs list to the end of "this" list how would i approach this? at the moment i have this but it does not seem to work:

BookList & BookList::operator+=( const BookList & rhs)
 {
  // Concatenate the righthand side book list of books to this list
  // by repeatedly adding each book at the end of the current book list
  // as long as it does not exceed <_capacity>
  // If exceeds, then stop adding
     
     for(int i = 0; i < _capacity; ++i) {
         this->_bookArray->_isbn += rhs._bookArray->_isbn;
         this->_bookArray->_title += rhs._bookArray->_title;
         this->_bookArray->_author += rhs._bookArray->_author;
         
     }
     
     return *this;
}

Upvotes: 1

Views: 174

Answers (1)

pvc
pvc

Reputation: 1180

Change your loop to below;

for(int i = 0; i < rhs._books_array_size; ++i) {
         
         if ( _books_array_size < _capacity )
         {
             _bookArray[_books_array_size] = rhs[i];
             _books_array_size++;
         }
     }

You need to loop the size of rhs array not _capacity of lhs, and add book at the of lhs array.

Upvotes: 1

Related Questions