【问题标题】:cannot convert argument 1 from 'int' to 'int &'无法将参数 1 从“int”转换为“int &”
【发布时间】:2018-11-25 18:05:15
【问题描述】:

我收到下一个错误,但找不到原因:

错误 C2664 'void SumID::operator ()(G &)':无法将参数 1 从 'int' 转换为 'int &'

为什么通过引用传递 int 存在问题?

我有下一堂课:

template <class T>
class SumID {
private:
    T sumid;

public:
    SumID():sumid()
    {
    }

    SumID(T s)
    {
        sumid = s;
    }

    T getSumID()
    {
        cout << "inside getSum";
        return sumid;
    }

    template <class G>
    void operator() (G& a)
    {
        sumid = sumid+ a;
    }
};

我的主要:

SumID<long> s;
for (int i = 0; i < 5; i++)
    s(5); // <-- error here

【问题讨论】:

  • 你可以做到,如果你把它放在一个变量中。只是5是一个常数值,不能赋值。
  • 5 = 17; 是什么意思?这就是为什么它是一个错误。
  • 使用右值引用 G&amp;&amp; a 绑定到临时对象。

标签: c++


【解决方案1】:

当使用 s(5); 时,参数 5 不是 左值。因此,当参数类型为G&amp;时不能使用。

您可以使用以下一种或两种方法解决问题。

  1. 创建一个变量并在调用中使用它。

    int x = 5;
    s(x);
    
  2. 将参数类型更改为 G、G&amp;&amp; 或 G const&amp;。

    template <class G>
    void operator() (G a)  // Or (G&& a) or (G const& a)
    {
       sumid = sumid+ a;
    }
    

【讨论】:

  • 或参数类型为 rvalue :void operator() (G&amp;&amp; a)
  • @JeJo,或者那个。感谢您的建议。
  • 所以在 C++ 中,当我传递左值时,我不能通过引用传递变量?为什么将参数的类型设置为 G&& 也可以解决问题?
  • 此外,解决方案 G &a const 引发了同样的错误。
  • @JeyJ s(5) 传递右值。并且它不能绑定到非常量引用(stackoverflow.com/questions/13826897/…)。 s(const G&amp;) 有效,因为它的 const 和 s(G&amp;&amp;) 有效,因为它不是右值引用,而是具有特殊规则的通用引用 (isocpp.org/blog/2012/11/…)。
猜你喜欢
  • 2015-06-12
  • 1970-01-01
  • 2014-04-02
  • 1970-01-01
  • 2015-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多