在C ++中将引用作为对象传递?

时间:2021-06-22 16:57:47

I know that C++ references are not objects, but seems that I can pass references as objects.

我知道C ++引用不是对象,但似乎我可以将引用作为对象传递。

In the code below, v1 and v2 are references, and are assigned as double &v1 = x1 through the constructor. Then, while calling from foo(), should I have bar(double &) or bar(double)? Based on double &v1 = x1, shouldn't there be bar(double)?

在下面的代码中,v1和v2是引用,并通过构造函数指定为double&v1 = x1。然后,在从foo()调用时,我应该有bar(double&)还是bar(double)?基于double&v1 = x1,不应该有bar(double)?

This looks confusing to me. Can someone explain it?

这让我感到困惑。有人可以解释一下吗?

#include <iostream>

class FooBar
{
private:
    double &v1, &v2;
public:
    FooBar(double &, double &);
    void foo();
    void bar(double &);
};

FooBar::FooBar (double &x, double &y): v1(x), v2(y) {}

void FooBar::foo()
{
    bar(v1);
    bar(v2);
}

void FooBar::bar(double &x)
{
    std::cout << x << "\n";
}

int main()
{
    double x1 = {0.5}, x2 = {1.5};
    FooBar f(x1, x2);
    f.foo();
    return 0;
}

1 个解决方案

#1


0  

Then while calling from foo(), should I have bar(double &) or bar(double)? Based on double &v1 = x1, shouldn't there be bar(double)?

然后在从foo()调用时,我应该有bar(double&)还是bar(double)?基于double&v1 = x1,不应该有bar(double)?

In this case it doesn't matter, v1 is a reference and if you change it inside of bar, the variable that was used to initialized it will also change, regardless if the parameter of bar is declared as double or double&.

在这种情况下无关紧要,v1是一个引用,如果你在bar中更改它,用于初始化它的变量也会改变,无论bar的参数是声明为double还是double。

Have in mind that a reference is like a synonym to a variable. Even though the C++ standard does not specify how a compiler must implement references, every C++ compiler I know implements references as pointers. So basically, you are passing the memory address of the variable to the function anyway.

请记住,引用就像变量的同义词。尽管C ++标准没有规定编译器必须如何实现引用,但我所知道的每个C ++编译器都将引用实现为指针。所以基本上,你无论如何都要将变量的内存地址传递给函数。

#1


0  

Then while calling from foo(), should I have bar(double &) or bar(double)? Based on double &v1 = x1, shouldn't there be bar(double)?

然后在从foo()调用时,我应该有bar(double&)还是bar(double)?基于double&v1 = x1,不应该有bar(double)?

In this case it doesn't matter, v1 is a reference and if you change it inside of bar, the variable that was used to initialized it will also change, regardless if the parameter of bar is declared as double or double&.

在这种情况下无关紧要,v1是一个引用,如果你在bar中更改它,用于初始化它的变量也会改变,无论bar的参数是声明为double还是double。

Have in mind that a reference is like a synonym to a variable. Even though the C++ standard does not specify how a compiler must implement references, every C++ compiler I know implements references as pointers. So basically, you are passing the memory address of the variable to the function anyway.

请记住,引用就像变量的同义词。尽管C ++标准没有规定编译器必须如何实现引用,但我所知道的每个C ++编译器都将引用实现为指针。所以基本上,你无论如何都要将变量的内存地址传递给函数。