gpt4 book ai didi

c++ - 定义函数的引用目的

转载 作者:行者123 更新时间:2023-11-30 01:55:15 25 4
gpt4 key购买 nike

我正在学习加速的 C++,并且对第 4 章有疑问。我们在本节中回顾了引用,我相信我理解它用于操作对象和变量的用途。然而,我真正不明白的是作者为什么要用&来重新定义一个已经属于std类的函数

代码如下:学生信息.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;
}

主要.cpp

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

有人可以解释一下我们为什么要这样做吗?只是出于教学原因来证明我们可以吗?提前致谢。

最佳答案

what I really don't understand is why the author uses & to redefine a function already belonging to std class

他没有重新定义函数。

他正在创建一个名为 read 的新函数,它返回一个 istream&

它返回引用的事实是约定俗成的(与标准库函数的等效行为相匹配),但与他首先定义函数的事实几乎没有关系。

标准库没有了解自定义类型 Student_info 的函数。

关于c++ - 定义函数的引用目的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20916770/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com