gpt4 book ai didi

c++ - 如何创建+ =运算符

转载 作者:行者123 更新时间:2023-12-02 10:09:47 25 4
gpt4 key购买 nike

我有一个包含类的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列表连接到“this”列表的末尾,我拥有所有我需要做的功能。我将如何处理呢?目前我有这个,但似乎不起作用:
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数组的大小,而不是 _capacitylhs,然后将书添加到 lhs数组的。

关于c++ - 如何创建+ =运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64148165/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com