如何创建一个+=运算符



我有一个hpp文件,其中包含一个类:

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

另一类是:


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

我有我需要做的所有函数,除了+=运算符,它需要将rhs列表连接到"的末尾;这个";列出我该如何处理?目前我有这个,但它似乎不起作用:

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

将循环更改为以下;

for(int i = 0; i < rhs._books_array_size; ++i) {

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

您需要循环rhs数组的大小,而不是lhs_capacity,并在lhs数组的处添加book。

最新更新