浮点对象及其值之间的区别
关于以下代码段:
struct Pair{
string name;
double val;
}
vector<Pair> pairs;
double& value(const string& s)
{
for (int i=0; i<pairs.size(); i++)
if (s==pairs[i].name) return pairs[i].val;
Pair p = {s,0};
pairs.push_back(p);
return pairs[pairs.size()-1].val;
}
作者声明
对于给定的参数字符串,value()查找对应的浮点对象(不是对应浮点对象的值);然后它返回对其的引用。
“浮点对象”和它的值有什么区别?
With respect to the following code segment:
struct Pair{
string name;
double val;
}
vector<Pair> pairs;
double& value(const string& s)
{
for (int i=0; i<pairs.size(); i++)
if (s==pairs[i].name) return pairs[i].val;
Pair p = {s,0};
pairs.push_back(p);
return pairs[pairs.size()-1].val;
}
The author states
For a given argument string, value() finds the corresponding floating-point object (not the value of the corresponding floating-point object); it then returns a reference to it.
What's the differce between "floating-point object" and its value?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
该对象是包含该值的实际内存块。
因此,如果您获得引用,您可以替换它的值,该值仍然存储在原始向量中。
当然,如果您只是获取值(通过将返回值更改为 double 而不带 &),您将无法更改中的实际值向量。
The object is the actual memory block that contains the value.
So if you get the reference you could replace its value, which is still stored in the original vector.
And of course if you'd just get the value (by changing the return value to double without the &) you wouldn't be able to change the actual value in the vector.
双& value(const string& s)
<- 它隐藏在这里。&
标记引用,而不是变量的值(如果您不知道引用是什么 - 它就像 const,非空指针)。double& value(const string& s)
<- it's hidden here.&
marks reference, not the value of variable (if you don't know what reference is - it's like const, not-null pointer).函数
value
不返回数字(例如3.1415或42),而是返回对变量的引用(技术术语是左值) 。它返回一个句柄,供您访问存储数字的实际对象(特别是您可以读取该数字),甚至可以修改它。也就是说:
将修改
name
字段为"foo"
的Pair
对象。如果现在这样做,
它将打印
42.314
。The function
value
doesn't return a number (eg. 3.1415 or 42) but a reference to a variable (the technical term is lvalue). It returns a handle for you to access the actual object storing the number (in particular you can read the number), and even modify it.To wit:
will modify the
Pair
object whosename
field is"foo"
.If now you do
it will print
42.314
.