简体   繁体   English

定义功能的参考目的

[英]Purpose of reference on defined function

I am going through accelerated c++ and have a question in regards to Chapter 4. We go over referencing in this section, and I believe I understand its use to manipulate objects and variables. 我正在学习加速的c ++,并且对第4章有疑问。我们在本节中不再赘述,并且我相信我理解它在处理对象和变量方面的用法。 However, what I really don't understand is why the author uses & to redefine a function already belonging to std class 但是,我真正不明白的是为什么作者使用&来重新定义已经属于std类的函数

Here is the code: Student_info.cpp 这是代码:Student_info.cpp

istream& read(istream& is, Student_info& s)
{
    // read and store the student's name and midterm and final exam grades
    is >> s.name >> s.midterm >> s.final;

    read_hw(is, s.homework);  // read and store all the student's homework grades
    return is;
}

main.cpp main.cpp

while (read(cin, record)) {
        // find length of longest name
        maxlen = max(maxlen, record.name.size());
        students.push_back(record);
    }

Could someone please explain why we would do this? 有人可以解释为什么我们会这样做吗? Is it just for pedagogical reasons to show that we can? 仅仅出于教学上的原因表明我们​​可以做到吗? Thanks in advance. 提前致谢。

what I really don't understand is why the author uses & to redefine a function already belonging to std class 我真正不明白的是为什么作者使用&重新定义已经属于std类的函数

He's not redefining a function. 他没有重新定义功能。

He's creating a new function, called read , that returns an istream& . 他正在创建一个名为read的新函数,该函数返回一个istream&

The fact that it returns a reference is convention (matching the equivalent behaviour of standard library functions) but has very little to do with the fact that he's defining the function in the first place. 它返回引用的事实是惯例(与标准库函数的等效行为匹配),但与他首先定义函数的事实没有任何关系。

The standard library has no function with knowledge of the custom type Student_info . 标准库不具有自定义类型Student_info知识的功能。

Because Student_info is a user-defined type and the istream operator needs to be overload it in order to know how to handle a Student_info parameter. 因为Student_info是用户定义的类型,并且istream运算符需要重载它才能知道如何处理Student_info参数。

Think about operator overloading with mathematical operators and the same thing applies. 考虑一下数学运算符的运算符重载,同样的情况也适用。

He uses & because he wants to return it as reference to the already created one so there is no unnecessary copy operations. 他之所以使用&,是因为他想返回它作为对已创建对象的引用,因此没有不必要的复制操作。

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

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