Error: initial value of reference to non-const must be an value
Error: initial value of reference to non-const must be an value
class A
{
public:
int v;
A * p;
A& operator*(const A& a)
{
return this->v*a.v// here is a red line under this say error initial value of reference to non-const must be an value
}
~A()
{
this;
}
};
int main()
{
A a;
a.p = new A;
delete a.p;
return 0;
system("pause");
return 0;
}
重载 * 运算符我不能用它来表示对象本身。为什么会这样。
当然它说它必须是一个左值。您正在尝试 return 对临时文件的引用。这是恶业。
而且,这根本不是你想要的。乘法运算符绝对应该 return 一个值,而不是一个引用。
不确定您的构造函数是什么样的,但假设它采用整数:
A operator * (A const& other) const
{
return A{ v * other.v};
};
编辑:
实际上你应该更进一步:
struct A
{
A& operator *= (A const& other) { v *= other.v; return *this; }
A(int i) : v(i) {}
private:
int v;
}
A operator * (A lh, A const& rh)
{
A res{std::move(lh)};
res *= rh;
return res;
}
this->v*a.v
的计算结果为 int
。 int
无法转换为 A&
。
使用
A operator*(const A& a) // Return a value, not a reference.
{
A res;
res.v = this->v*a.v;
return res;
}
您也应该将成员函数设为 const
成员函数,因为它不会修改对象。
A operator*(const A& a) const
{
A res;
res.v = this->v*a.v;
return res;
}
this->v * a.v
的结果是一个 rvalue,一个临时未命名的值。作为临时,它不能绑定到 非常量 引用。只有 lvalues 可以绑定到 non-const 引用。这就是错误 "initial value of reference to non-const must be an lvalue" 所指的内容。
但是,您也不想 return const 引用,您想要 return 按值 return 值:
A operator*(const A& a) { … }
^ remove &
注意:这不会完全修复您的代码,因为您正在尝试 return 一个 int
,其中您声明 return 一个 A
,并且 int
在您当前的代码中不能隐式转换为 A
。
class A
{
public:
int v;
A * p;
A& operator*(const A& a)
{
return this->v*a.v// here is a red line under this say error initial value of reference to non-const must be an value
}
~A()
{
this;
}
};
int main()
{
A a;
a.p = new A;
delete a.p;
return 0;
system("pause");
return 0;
}
重载 * 运算符我不能用它来表示对象本身。为什么会这样。
当然它说它必须是一个左值。您正在尝试 return 对临时文件的引用。这是恶业。
而且,这根本不是你想要的。乘法运算符绝对应该 return 一个值,而不是一个引用。
不确定您的构造函数是什么样的,但假设它采用整数:
A operator * (A const& other) const
{
return A{ v * other.v};
};
编辑:
实际上你应该更进一步:
struct A
{
A& operator *= (A const& other) { v *= other.v; return *this; }
A(int i) : v(i) {}
private:
int v;
}
A operator * (A lh, A const& rh)
{
A res{std::move(lh)};
res *= rh;
return res;
}
this->v*a.v
的计算结果为 int
。 int
无法转换为 A&
。
使用
A operator*(const A& a) // Return a value, not a reference.
{
A res;
res.v = this->v*a.v;
return res;
}
您也应该将成员函数设为 const
成员函数,因为它不会修改对象。
A operator*(const A& a) const
{
A res;
res.v = this->v*a.v;
return res;
}
this->v * a.v
的结果是一个 rvalue,一个临时未命名的值。作为临时,它不能绑定到 非常量 引用。只有 lvalues 可以绑定到 non-const 引用。这就是错误 "initial value of reference to non-const must be an lvalue" 所指的内容。
但是,您也不想 return const 引用,您想要 return 按值 return 值:
A operator*(const A& a) { … }
^ remove &
注意:这不会完全修复您的代码,因为您正在尝试 return 一个 int
,其中您声明 return 一个 A
,并且 int
在您当前的代码中不能隐式转换为 A
。