如何在此代码中返回工作?

时间:2015-06-30 13:03:11

标签: c++

它是如何工作的?

struct Person
{
    std::string name;
    std::string address;
};

std::istream &read(std::istream &is, Person &person)
{
    is>> person.name;
    getline(is, person.address);
    return is;
}

int main()
{ 
    Person p; 
    read(cin,p);
}

return is person.name如何同时返回person.addressgetlineis似乎与.fileinfo分开?

1 个答案:

答案 0 :(得分:6)

The function returns a single value, it can't return more. In this case, it returns by reference the stream that it got as the first parameter, also by reference. The person's name and address are not returned, they are read from the stream and used to fill the Person instance p received by reference.

// notice both parameters are references
std::istream &read(std::istream &is, Person &person)
{
    is >> person.name; // read the name and store it in the person object
    getline(is, person.address); // read the address and store it in the person object
    return is; // return the stream reference
}

int main()
{ 
    Person p; 
    read(cin,p); // both params are sent by reference
    // so here the object p will have it's members properly filled
}

Returning the stream by reference as you do for your read() function doesn't make much sense in this situation. This is usually done for overloading operators for streams, e.g.:

std::istream& operator >>(std::istream &is, Person &person)
{
    is >> person.name;
    is >> person.address;
    return is;
}

In this case it is useful to return the stream because this way you can chain multiple calls, for example:

Person p1, p2, p3;
std::cin >> p1 >> p2 >> p3;

In your case this is not really useful and it would actually hurt readability if you chained the calls:

Person p1, p2, p3;
read(read(read(cin, p1), p2), p3);

In this case it is much easier, both to write and to read, if you do it like this:

Person p1, p2, p3;
read(cin, p1);
read(cin, p2);
read(cin, p3);