Jump to content
  • Advertisement
Sign in to follow this  
Ksingh30

Operator overloading

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

If you intended to correct an error in the post then please contact us.

Recommended Posts

Advertisement
From google's first hit: (assuming, of course, that you meant C++)

// vectors: overloading operators example
#include <iostream.h>

class CVector {
public:
int x,y;
CVector () {};
CVector (int,int);
CVector operator + (CVector);
};

CVector::CVector (int a, int b) {
x = a;
y = b;
}

CVector CVector::operator+ (CVector param) {
CVector temp;
temp.x = x + param.x;
temp.y = y + param.y;
return (temp);
}

int main () {
CVector a (3,1);
CVector b (1,2);
CVector c;
c = a + b;
cout << c.x << "," << c.y;
return 0;
}


This is a really easy example and it was really easy to find *hint* *hint*.
If you need explanation, visit the site where I found it and read it and if there is still something unclear then you can ask us :)
I'm willing to explain it in detail (although I might go to sleep soon but I'm sure there will be others)

Share this post


Link to post
Share on other sites
FWIW, it's generally considered better to implement binary operators as (possibly friend) non-member functions. Among other things, it enables conversion on the left argument.

class CVector 
{
public:
int x,y;
CVector () {};
CVector (int,int);
friend CVector operator + (const CVector&, const CVector&);
};



CVector::CVector (int a, int b)
{
x = a;
y = b;
}


CVector operator+ (const CVector& lhs, const CVector& rhs)
{
return CVector(lhs.x+rhs.x, lhs.y+rhs.y);
}


int main () {

CVector a (3,1);
CVector b (1,2);
CVector c;

c = a + b;

cout << c.x << "," << c.y;

return 0;
}

Share this post


Link to post
Share on other sites
Um, Fruny, you just friended a non-member function that only uses public variables. Also if you implement the binary operator+(), you should really implement operator+=() (and strongly consider implementing operator+() in terms of operator+=()).

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!