为什么变量会自动通过引用传递?

Whe*_*050 1 c++

我试图在ROOT绘图包中调用一个接受三个变量的函数.我的代码中的相关部分是:

int xwidth=0,ywidth=0;
Bool_t useangle=0;
vIt->GetBoundingBox(xwidth,ywidth,useangle);
Run Code Online (Sandbox Code Playgroud)

其中vIt是GetBoundingBox作为类成员函数的对象的迭代器.(Bool_t只是ROOT使用的typedef).

现在,当我编译时,我从g ++中得到以下错误:

error: no matching function for call to ‘TText::GetBoundingBox(int&, int&, Bool_t&)’
/home/bwhelan/Programs/MODIFIED//External/root/5.30.00/include/root/TText.h:57: note:   candidates are: virtual void TText::GetBoundingBox(UInt_t&, UInt_t&, Bool_t)
Run Code Online (Sandbox Code Playgroud)

我的问题是为什么在这里通过引用传递useangle而不是值?我根本想不出来.

Seb*_*ach 8

在C++中,在重载解析时,会选择一组可行的重载,并且选择需要转换次数最少的一个候选(它是否需要更改const??是否需要提升整数到浮点?).如果有多个具有相同权重的匹配项,则会出现模糊调用并出现错误(例如:int foo(int &x, int y); int foo(int x, int &y); ... int a,b; foo(a,b);不明确).

然而,在你的情况下,没有有效的转换过程中可以发现,因为从不存在有效转换 int&unsigned int&(旁注:有从存在转换intunsigned int反之亦然),因为不相关类型的引用是不兼容的.

关于错误消息:编译器使用最弱的允许绑定来过滤掉可行功能集.因为int,这是int&.但由于找不到可行的函数集,因此会出现错误消息.消息的作者不是基于您的代码,而是基于他/她搜索的数据,即int&.然而,他/她正确地提出了一种真正存在的可行替代方案.

因此,我们在这里有更多的编译器诊断质量问题,而不是C++ 正确性问题.


从标准来看,这是转换表.使函数调用有效所需的最少,匹配越好:

Conversion                         
-----------------------------------+----------------------------
No conversions required            | Identity
-----------------------------------+----------------------------
Lvalue-to-rvalue conversion        | Lvalue transformation
Array-to-pointer conversion        |
Function-to-pointer conversion     |
-----------------------------------+----------------------------
Qualification conversions          | Qualification adjustment
-----------------------------------+----------------------------
Integral promotions                | Promotion
Floating point promotion           |
-----------------------------------+----------------------------
Integral conversions               | Conversion
Floating point conversions         |
Floating-integral conversions      |
Pointer conversions                |
Pointer to member conversions      |
Boolean conversions                |
-----------------------------------+----------------------------
Run Code Online (Sandbox Code Playgroud)