繁体   English   中英

类和变量之间的“与号运算符”是什么意思?

[英]What does "ampersand operator" mean between a class and a variable?

我在 plumed 中看到以下代码并且很困惑:

void ActionAtomistic::makeWhole() {
for(unsigned j=0; j<positions.size()-1; ++j) {
    const Vector & first (positions[j]);
    Vector & second (positions[j+1]);
    second=first+pbcDistance(first,second);
  }
}

谁能告诉我这里使用的“&”是什么? 我在 google 上搜索了“类和变量之间的 c++ &符号”,但没有找到答案。

更新:我知道参考是什么,但认为 Vector 和“&”之间不应该有任何空格。 谢谢你们澄清这一点。

这意味着firstVector类型对象的引用(在本例中为const引用),而不是Vector类型的对象。

在此处阅读有关参考资料的更多信息。

这被称为参考。 我通常会写类似Type& name的引用,以明确引用是类型的一部分。

引用就像是更容易使用但有一些限制的指针。 以下是您何时可以使用参考的示例:

void add1ToThisNumber(int& num) {
    num += 1;
}
// elsewhere...
int myNumber = 3;
add1ToThisNumber(myNumber);
cout << myNumber; // prints 4

引用(在这种情况下)基本上是另一个变量的别名。 虽然以下不适用于第一种情况(因为您的引用是const ),但引用可用于修改它们所引用的对象。 举个例子:

int c = 5;
int& d = c;
d = 12; // c is set to 12

在您的特定情况下,引用是一个不可变的别名,因此不能通过first修改 points positions[j]

在第二种情况下,执行second = variable将评估为positions[j + 1] = variable

&根据上下文具有不同的含义。

  1. 声明一个类型。

     int var; int& ref1 = var; // Declares a reference to a variable int const& ref2 = var; // Declares a const reference to a variable int& foo(); // Declares foo() whose return type is reference to an int void bar(int&); // Declares bar whose argument type is reference to an int struct Foo { int& bar; // Declares bar to be member variable of the // class. The type is reference to an int };
  2. 获取变量的地址(实际上是任何左值)

     int var; int* ptr = &var; // Initializes ptr with the address of var int arr[4]; int* ptr2 = &(arr[3]); // Initializes ptr2 with the address of the // last element of arr
  3. 执行按位与运算。

     int i = <some value>; int j = <some value>; int k = (i & j); // Initializes k with the result of computing // the bitwise AND of i and j

您在代码中的内容是第一次使用。

const Vector & first (positions[j]);

该行first声明为对position[j]const引用。

暂无
暂无

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

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