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.
this->v*a.v
evaluates to anint
. Anint
cannot be converted to anA&
.Use
You should make the member function a
const
member function too since it does not modify the object.The result of
this->v * a.v
is an rvalue, a temporary unnamed value. As a temporary, it cannot bind to a non-const reference. Only lvalues can bind to non-const references. That's what the error "initial value of reference to non-const must be an lvalue" is referring to.However, you don't want to return a const reference either, you want to return the value by value:
Note: this will not fix your code completely as you're trying to return an
int
where you declared to return anA
, andint
isn't implicitly convertible toA
in your current code.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:
Edit:
And actually you should go a step further: