简体   繁体   English

此代码中的return如何工作?

[英]how does return work in this code?

how does it work? 它是如何工作的?

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);
}

how return is returns both person.name and person.address together while getline seems to be apart from is ? 如何return is收益都person.nameperson.address在一起,同时getline似乎除了is

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. 人员的名称和地址不会返回,而是从流中读取并用于填充通过引用接收的Person实例p

// 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. 在这种情况下,像您对read()函数所做的那样按引用返回流没有太大意义。 This is usually done for overloading operators for streams, eg: 这通常是针对流的重载运算符来完成的,例如:

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM