Tried to overload operator+
but looks like there is an unwanted side effect, it modifies one of the arguments. How am I supposed to do it?
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class BookShelf
{
vector<string> m_books;
public:
BookShelf(const vector<string>& books)
: m_books(books)
{
}
BookShelf& operator+(const BookShelf& bookshelve)
{
for (const auto& b : bookshelve.m_books)
m_books.push_back(b);
return *this;
}
void print()
{
for (const auto& book : m_books)
cout << book << " ";
cout << endl;
}
};
int main()
{
BookShelf b1{{"abc", "def"}};
b1.print();
BookShelf b2{{"ghi", "jlm", "nop"}};
b2.print();
BookShelf b3 = b1 + b2;
b3.print();
b1.print();
b2.print();
}
The above returns:
abc def
ghi jlm nop
abc def ghi jlm nop
abc def ghi jlm nop
ghi jlm nop