错误:对非const的引用的初始值必须是一个值 [英] Error: initial value of reference to non-const must be an value
本文介绍了错误:对非const的引用的初始值必须是一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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;
}
重载*运算符我不能使用它来表示对象本身.为什么会这样.
overloading * operator I cannot use this to represent the object itself. Why this happened.
推荐答案
当然,它说它必须是 lvalue .您正在尝试返回对临时目录的引用.这是不好的业力.
Surely it says that it must be an lvalue. You're trying to return a reference to a temporary. This is bad karma.
此外,它根本不是您想要的.乘法运算符绝对应该返回一个值,而不是引用.
Besides, it's not at all what you want. The multiplication operator should definitely return a value, not a reference.
不确定您的构造函数是什么样子,但假设它采用整数:
Not sure what your constructor looks like, but assuming it takes an integer:
A operator * (A const& other) const
{
return A{ v * other.v};
};
实际上,您应该更进一步:
And actually you should go a step further:
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;
}
这篇关于错误:对非const的引用的初始值必须是一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文