Reputation: 95
Sorry if a question similar is posted about this already, but I don't know how to word this question properly. How can I access "William" and "Shakespeare" with cout << that was passed into Author object shakespeare, which was then passed into the vector of authors which was then passed into the Book object play?
class Author{} //has private variables first_name and last_name and getter
//functions in public.
class Book{
private:
vector<Author> author_mem;
public:
Book(const vector<Author>& author_fn):author_mem(author_fn){}
vector<Author> get_author_list() const {return author_mem;}
}
int main(){
const Author shakespeare("William","Shakespeare");
const vector<Author> authors = {shakespeare};
const Book play(authors);
//initiial idea was to have something like
//cout << play.get_author_list.at(0)
}
Upvotes: 0
Views: 75
Reputation: 33952
Put something along the lines of this into your Author class to overload the << operator:
friend std::ostream &operator<<(std::ostream &output, const Author & author)
{
output << //this depends on how you stored the data in Author probably
// output << author.firstname << " " author.lastname;
}
Then cout << play.get_author_list().at(0)
will work.
Consider adding Author& get_author(size_t index)
and size_t get_author_listsize()
methods so that you don't have to expose the vector inside Book. No point handing around private data, and you may want to replace the container one day.
Or even more fun:
typedef vector<Author>::iterator AuthorIterator;
and then
AuthorIterator getAuthorBegin()
{
return author_mem.begin();
}
AuthorIterator getAuthorEnd()
{
return author_mem.end();
}
Upvotes: 1
Reputation: 3054
I don't know how you named your accessors for your Author
class, but let's say it's GetFirstName
and GetLastName
.
That should work:
cout << play.get_author_list().at(0).GetFirstName();
cout << play.get_author_list().at(0).GetLastName();
Upvotes: 3