class Person {
...
};
class Book {
private:
...
Person *person;
...
public:
...
Person *getPerson() {return person;}
void setPerson(Person *_person) {person = _person;}
...
};
class Library {
private:
vector<Book> books;
vector<Person> people;
public:
vector<Book> getBooks() {return books;}
vector<Person> getPeople() {return people;}
void addBook(Book _book) {//adds a Book to books}
void addPerson(Person _person) {//adds a Person to people}
bool checkOut(Person *_person, Book *_book) {
if (_book->getPerson() == NULL ) {
_book->setPerson(_person);
return true;
}
else {
return false;
}
}
int main() {
Library lib("My Library");
Book b1("The C Programming Language", "Brian Kernighan and Dennis Ritchie");
Book b2("Unknown Title", "Unknown Author");
Book b3("Burning Daylight", "Jack London");
Person p1("John");
Person p2("Peter");
Person p3("Ann");
lib.addPerson(p1);
lib.addPerson(p2);
lib.addPerson(p3);
lib.addBook(b1);
lib.addBook(b2);
lib.addBook(b3);
lib.checkOut(&lib.getPeople().at(1), &lib.getBooks().at(1));
return 0;
}
程序运行。如果我将 setPerson 放在 Book 类的构造函数中,那么它可以工作。为什么当我从 Library 类调用 checkOut 方法时它不起作用?为什么 checkOut 方法没有在 Book 类中设置 Person ,尽管它返回 true ?我不明白什么?谢谢!