Our Professor has given us a practice test with the answers to help us for our upcoming test. I don't understand how the answer for this code is 135
.
I understand what a class is but I am struggling how operators work. For v{6}
I understand that for the object v
the int v
equals 13
. I thought that in the int main that the first -v
in (-v - v).print
would be evaluated first in the operator that return 2 * v
and that it would return 26
. I then thought they would then be put in the last operator
V operator-(int lop, const V& rop)
{
return rop - lop;
}
but I don't think that is the case. I have put this code into Visual Studio to mess around with it but I don't understand what is going on.
#include <iostream>
using namespace std;
class V
{
int v;
public:
V(int a = 3, int b = 7) : v{a + b}
{
}
void print()
{
cout << v;
}
V operator-(const V& rop) const
{
return (3 * v) + (2 * rop.v) + 3;
}
V operator-()
{
return 2 * v;
}
};
V operator-(int lop, const V& rop)
{
return rop - lop;
}
int main()
{
V v{6};
(-v - v).print();
return 0;
}
Wow, this is confusing code, with re-used variable names, strange unconventional operations and such. The code is particularly hard to follow because V
can be implicitly constructed from an integer, with 7 always added to that integer; even with a debugger, this took me a few moments to grok. Please never write code like this, not even for fun!
The result of -v
in main
is not an int
. It is a V
object implicitly constructed from the expression 2 * v
(=26), resulting in a member integer with value 33 (26+7).
It's as if you wrote:
V operator-()
{
return V(2 * v);
}
or, due to the default argument:
V operator-()
{
return V(2 * v, 7);
}
Then you take this new returned object and feed it to member operator-(const V&)
; same story applies. It produces the expression 3*33 + 2*13 + 3
, which is 128; again this is used to construct a new V
(because that's the return type!), so add 7 to get 135.
operator-(int lop, const V& rop)
doesn't come into it because you never performed a subtraction between an int
and a V
.
The result of -v
is not an int
, but a V
.
Thus, the member-overloaded subtraction will be used.
This is the equivalent code, without the syntactic sugar of operators, but with explicit conversion of return values:
class V
{
public:
V(int a = 3, int b = 7) : v{a + b}
{
}
void print()
{
cout << v;
}
V subtract(const V& rop) const
{
return V((3 * v) + (2 * rop.v) + 3);
}
V negate()
{
return V(2 * v);
}
private:
int v;
};
int main()
{
V v{6};
(v.negate().subtract(v)).print();
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.