Operator overloading

Hi there,
I've been experimenting with operator overloading, and I can't seem to overload the * operator where the right hand side operand is a plain integer (i.e. only the lhs is a member of the class). Should that be the case, or am I doing something wrong?
Basically, my class has three integer members, and I want to overload * to be able to multiply all members by the same integer.
Thanks!
I like linking to this: http://stackoverflow.com/questions/4421706/operator-overloading/4421708#4421708
Tons of operator overloading questions are answered all on that one page. But anyways on to your question...
1
2
3
4
5
6
7
8
9
10
11
12
struct vec
{
    int x, y, z;
};

inline vec operator*(vec lhs, const int& rhs)
{
    lhs.x *= rhs;
    lhs.y *= rhs;
    lhs.z *= rhs;
    return lhs;
}
Last edited on
Thanks for the quick reply!

I've been trying to do it as a member function, and I just can't work out what I'm doing wrong.
I have overloaded the + operator in the same class, and it works perfectly.
The only difference I can see is that with my + overload both operands are members of my class, but with my * overload, only the lhs is. Could that be a reason for my problem?
I've actually worked out what I've done wrong, but I can't work out how to get round it!

It happened to be that when I was using my * overload, my lhs operand was a const. When I changed it to not being const, it worked.

I imagine that's because the lhs operand gets automatically passed as not const - but how do I change that?

Thanks.

Edit to add: Worked it out! Just had to add const after the parameter's in the operator overload function.
Last edited on
Topic archived. No new replies allowed.