将vector <class> myvector传递给构造函数并访问它

时间:2015-06-03 01:04:59

标签: c++ oop

很抱歉,如果已经发布了类似的问题,但我不知道如何正确地说出这个问题。我如何访问&#34; William&#34;和#34;莎士比亚&#34;与cout&lt;&lt;那是传递给作者对象莎士比亚,然后传递给作者的载体,然后传递给Book对象播放?

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)

}

2 个答案:

答案 0 :(得分:3)

我不知道你如何为Author课程命名你的访问者,但我们说它是GetFirstNameGetLastName

这应该有效:

cout << play.get_author_list().at(0).GetFirstName();
cout << play.get_author_list().at(0).GetLastName();

答案 1 :(得分:1)

将一些内容添加到Author类中以重载&lt;&lt;操作者:

elementFromPoint()

然后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; } 将有效。

考虑添加cout << play.get_author_list().at(0)Author& get_author(size_t index)方法,这样您就不必在Book中公开向量。无需处理私人数据,您可能希望有一天更换容器。

或者更有趣:

size_t get_author_listsize()

然后

typedef vector<Author>::iterator AuthorIterator;