【问题标题】:invalid initialization of non-const reference of type ‘Matrix&’ from an rvalue of type ‘Matrix’从“Matrix”类型的右值初始化“Matrix&”类型的非常量引用无效
【发布时间】:2017-10-27 18:51:01
【问题描述】:

我有一个矩阵类,它有一组函数,其中一个是 Matrix operator++();

构造函数:

Matrix(int num_rows,int num_col,int initialization,double initializationValue)
{
this->num_rows=num_rows;
this->num_col=num_col;
if((num_rows*num_col)==0){values=NULL;return;}
values = new double*[num_rows];
for(int index_row=0;index_row<num_rows;index_row++)
{
    values[index_row]=new double[num_col];
    for(int index_col=0;index_col<num_col;index_col++)
    {
        switch(initialization)
        {
            case MI_ZEROS: values[index_row][index_col] =0; break;
            case MI_ONES: values[index_row][index_col]=1;break;
            case MI_EYE: values[index_row][index_col]=(index_row==index_col)? 1:0;break; //I matrix
            case MI_RAND: values[index_row][index_col]=(rand()%1000000)/1000000.0;break;
            case MI_VALUE: values[index_row][index_col]=initializationValue;break;
        }
    }

  }
}  

添加函数:

void Matrix::add(Matrix& m)
{
if(num_rows!=m.num_rows||num_col!=m.num_col)
  throw("Invalid Matrix dimensions for add operation");

 for(int iR=0; iR<num_rows; iR++ )
  for(int iC=0; iC<num_col; iC++)
    values[iR][iC] += m.values[iR][iC];
}

当我尝试这样定义它时:

Matrix Matrix::operator++()
{
const double d = 1.0;
add(Matrix(num_rows, num_col, MI_VALUE, d));
return  *this;
}

我得到这个错误:

matrix.cpp:367:45: 错误:从“Matrix”类型的右值初始化“Matrix&”类型的非常量引用无效

add(矩阵(num_rows, num_col, MI_VALUE, d));

注意:初始化'void Matrix::add(Matrix&)'的参数1 void Matrix::add(Matrix& m)

我真的不明白为什么会出现这个问题以及如何解决它,因为它在许多不同的功能中经常发生,我该如何解决这个问题?

注意:我使用的是 ubuntu 16.04 和一个 g++ 编译器。

【问题讨论】:

  • Matrix::operator++() 应该返回 Matrix&amp;
  • 可能是因为您的 add 函数的签名为 add(Matrix&amp;) 而不是 add(const Matrix&amp;) 如果您想保留原始的 add 签名,即左值对象,请添加一个 add(Matrix&amp;&amp;) 类型的新签名
  • 请显示add
  • 如果您停止隐藏变量,则不需要 this-&gt;num_rows=num_rows; 中的 this-&gt;

标签: c++ matrix g++


【解决方案1】:

您没有在帖子中包含add 的代码,但我可以从错误中看到它具有签名void Matrix::add(Matrix&amp; m)。这里Matrix&amp; 表示你传递的对象必须是l-value。粗略地说,如果一个对象有名字,它就是左值,而临时变量没有。

您必须更改add 函数的签名:它必须是add(Matrix a)add(const Matrix&amp; a)。在第一种情况下,函数接收对象的副本。在第二种情况下,它接收一个常量引用,并且临时对象可以绑定到常量引用。后者是首选,因为不会制作不必要的副本。

如果你不打算在你的函数中修改它们,千万不要通过引用传递参数(没有const)。首选const Type&amp;

【讨论】:

  • 它通过在签名中添加 const 解决了我的问题。非常感谢
  • 或者,只是按值传递,有时(通常)实际上更快更容易推理。
  • @HossamSalah 欢迎您!如果对您有帮助,请考虑接受我的回答(左侧的“V”标记)。
猜你喜欢
  • 2017-09-08
  • 2020-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-07
  • 2021-10-26
  • 1970-01-01
  • 2015-01-26
相关资源
最近更新 更多