Archived

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

sic_nemesis

construtors and such

Recommended Posts

im not terribly good with overloading operators or created copy constructors.etc.. so can i get a little input on if i did this right or not?
struct point2D
{
        float x,y;
    point2D():x(0),y(0){};
    point2D(float _x,float _y):x(_x),y(_y){};
    
};
point2D operator+(const point2D &lhs, const point2D &rhs)
{
    lhs.x+=rhs.x;
    lhs.y+=rhs.y;
    return lhs;
}
point2D operator-(const point2D &lhs, const point2D &rhs)
{
    lhs.x-=rhs.x;
    lhs.y-=rhs.y;
    return lhs;
}
 
for ease of use im probably going to add overloaded functions for doubles and ints with that code, could i do this: point2d x(2,3); point2d y=(2,1); void funct(point2D poo); funct(1,3); point 2d x,y,z; x=y+z; x=y-z; x+=y; x-=z; and what is the pooint of making a function a freind of a class? i never understood that (i think i fell alseep in class)

Share this post


Link to post
Share on other sites
point2D():x(0),y(0){};
point2D(float _x,float _y):x(_x),y(_y){};

Add a copy constructor:
point2D(const point2D & p):x(p.x),y(p.y){}

point2D operator+(const point2D &lhs, const point2D &rhs);
Should be:
point2D operator+(const point2D &rhs)
{
point2D result(x + rhs.x, y + rhs.y);
return result;
}

This is because the expression a = b + c equates to the logic a = b.operator + (c);.

quote:

with that code, could i do this:
...
point2d y=(2,1);

Um, no. (2,1) is not any intrinsic or compound type, so your overloaded operator= can''t take it as an argument.
quote:
funct(1,3);

See above.

quote:

and what is the pooint of making a function a freind of a class? i never understood that (i think i fell alseep in class)

The friend function is a non-member, but has access to private class/object data. Some people have operator+ and operator- as friend methods.

Share this post


Link to post
Share on other sites