#### Archived

This topic is now archived and is closed to further replies.

# operators: a * (-b)

This topic is 5563 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

i''ve got a simple class looking like this

class example
{
private:
int i1, i2;
}

now i want to do stuff like:

example e1, e2, e3;
//filling e1, e2 with content

e3 = e1 * (-e2)

how do i define the operator in front of e2 so that it multiplicates every value with (-1)? [ps] multiplicating is not the problem but defining the operator

##### Share on other sites

    class example{  int i1, i2;public:  example(int i = 0, int j = 0)   : i1(i), i2(j)  {}  example operator * (const example& e) const  {     return example(i1 * e.i1, i2 * e.i2);  }  example operator - () const  {     return example(-i1, -i2);  }};

[edited by - sark on December 1, 2002 9:07:48 AM]

##### Share on other sites
thx... did not think it was that easy

sry for doublepost
edit by ze: Then do something about it. It's very possible to simply click "Edit" and then check the double-post box and "Make Modifications." Deleted double post.

[edited by - zealouselixir on December 1, 2002 4:31:53 PM]

##### Share on other sites
Hrm. I got my doubts with that post... You are overloading the ''-'' operator to make everything negative... but this means you can''t do ''e1 - e2'' anymore, you would have to do ''e1 + -e2''. I don''t have experience with operator overloading, but this seems like a problem to me ^_^ Doesn''t C++ make a difference between the two different uses of ''-''?

##### Share on other sites
Notice that there aren''t any parameters for the - operator that was overloaded. If you wanted to do e1 - e2, then you would overload the - operator again, with an example as a parameter.

  example example::operator -(const example &rhs){     return(example((i1 - rhs.i1), (i2 - rhs.i2)));}    // end -

##### Share on other sites
Ah, thank you ^_^ Seems I got overloading a bit wrong then :D

##### Share on other sites
quote:
Original post by YoshiN
Notice that there aren''t any parameters for the - operator that was overloaded. If you wanted to do e1 - e2, then you would overload the - operator again, with an example as a parameter.

    example example::operator -(const example &rhs){     return(example((i1 - rhs.i1), (i2 - rhs.i2)));}    // end -

yep... i knew hot to overloading the - operator for ''a-b''... but i did not knew how to use the same operator for (-a).