0
class Person {
.....
}    
class Book {
    string title;
    Person person;
    ....
    Person getPerson() {
        return person;
    }
    ....
}

int main() {
Person p1;
Book b1;

b1.setPerson(p1);

b1.getPerson();


}

我的问题是 b1 中 person 的值是什么, b1.getPerson() 返回什么?如何检查该字段是否有值?我想检查这本书是否有分配的人,如果没有,然后分配一个人。

  bool isPerson(Person _person, Book _book) {
        if (_book.getPerson() == NULL) {
            _book.setPerson(_person);
            return true;
        }
        else {
            return false;
        }

这是我想做的,但是 ==NULL 是不正确的。

谢谢!

4

4 回答 4

1

如前所述,将调用 Person 类的默认构造函数。如果您没有编写自己的构造函数(将调用默认构造函数)并且没有在构造函数中初始化实例的任何成员,则成员将包含发生内存分配时内存中的值。

在这种情况下,它将只包含堆栈上的垃圾(因为它是在堆栈上分配的。)

于 2013-10-14T14:39:53.903 回答
1

You have at least two options:

1 Use pointers

That's the option you seem to want to go for with using NULL and stuff... if the person for the book is really optional, you can make a pointer (or even better, a shared_ptr or some other smart pointer) out of the person member to make it possible to have the state "person not set", e.g.

class Book {
    string title;
    std::shared_ptr<Person> person;
    void getPerson(std::shared_ptr<Person> p) {
         return person = p;
    }

    std::shared_ptr<Person> getPerson() {
         return person;
    }
};

You'll have to access members of that person with -> then though (e.g., let's assume person has a constructor taking the name, and a getName function:) - of course you'll have to be careful to not dereference an unset pointer, just as well as with raw pointers (or with the references in Java, where to me it seems you might come from?).

Book b1;
// ... set Person ...
b1.setPerson(std::make_shared<Person>("John"));

Then you can check if person is set simply by checking the default bool operator of the std::shared_ptr, like this:

// somewhere in Book class:
if (person) ...

2 "Empty" convention

Make a convention for what it means for a person to be unset (e.g. that when the name is empty, it is the "default", i.e. unset person). Then you can simply check in Book class:

if (person.getName().empty()) ...

Notice however that with this option you're more likely to run into problems when your Person class changes, as it is now tightly coupled into the Book class. E.g. at some point you might require for the Person's name to actually be set on construction, you'd have to change your logic in Book as well.

于 2013-10-14T14:50:43.780 回答
0
class Book
{
private:
    Person p1;
public:
    Book()
    { }

    friend bool operator== (const Book& b, const Person& p)
    {
        return &b.p1 == &p;
    }
};
于 2013-10-14T14:51:20.707 回答
0

它将返回您Person创建的默认构造函数。

于 2013-10-14T14:32:55.103 回答