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;
}
重载 * 运算符 我不能用它来表示对象本身。为什么会这样。
最佳答案
当然它说它必须是一个左值。您正在尝试返回对临时文件的引用。这是恶业。
此外,这根本不是你想要的。乘法运算符绝对应该返回一个值,而不是一个引用。
不确定您的构造函数是什么样的,但假设它采用整数:
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;
}
关于c++ - 错误 : initial value of reference to non-const must be an value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33001702/