简体   繁体   English

浮点对象及其值之间的区别

[英]Difference between floating-point object and its 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); 对于给定的参数字符串,value()查找相应的浮点对象(而不是相应的浮点对象的值); it then returns a reference to it. 然后返回对其的引用。

What's the differce between "floating-point object" and its value? “浮点对象”与其值之间有何区别?

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. 当然,如果仅获取值(通过将返回值更改为不带&的 double值),则将无法更改向量中的实际值。

double& value(const string& s) <- it's hidden here. double& value(const string& s) <-隐藏在这里。 & marks reference, not the value of variable (if you don't know what reference is - it's like const, not-null pointer). &标记引用,而不是变量的值(如果您不知道引用是什么-就像const,not-null指针)。

The function value doesn't return a number (eg. 3.1415 or 42) but a reference to a variable (the technical term is lvalue ). 函数value不返回数字(例如3.1415或42),而是返回对变量引用 (技术术语为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: 以机智:

value("foo") = 42.314;

will modify the Pair object whose name field is "foo" . 将修改name字段为"foo"Pair对象。

If now you do 如果现在做

std::cout << value("foo") << "\n";

it will print 42.314 . 它会打印42.314

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

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