The first project I did in c++ worked... but in retrospect it was horrible not object oriented. >.> I thought classes and structs were pretty much the same as user defined types in DBPro...
Since then, I've taken a java class, and I've made a bunch of object-oriented things in java, and I get it. Now, moving back to c++, I need to check my work.
I've made a basic 2d vector class, with operator overloading, to be able to do vector math easily. My question is: Does the following code follow standard conventions, handle stuff safely, and most importantly, does it work?
class vector2
{
public:
float x;
float y;
vector2();
vector2(const float& a,const float& b);
vector2 operator+ (const vector2& b); //vector addition
vector2& operator+= (const vector2& b);
vector2 operator- (const vector2& b); //vector subtraction
vector2& operator-= (const vector2& b);
vector2 operator* (const float& b); //vector scalar multiplication
vector2& operator*= (const float& b);
vector2 operator/ (const float& b); //vector scalar division
vector2& operator/= (const float& b);
float operator* (const vector2& b); //dot product
void normalize();
void normalize(const float& dist);
float length();
};
//class vector2
//{
vector2::vector2()
{
x = y = 0.0f;
}
vector2::vector2(const float& a,const float& b)
{
x=a;
y=b;
}
vector2 vector2::operator+ (const vector2& b)
{
vector2 temp;
temp.x=x+b.x;
temp.y=y+b.y;
return temp;
}
vector2& vector2::operator+= (const vector2& b)
{
if(this!=&b)
{
x=x+b.x;
y=y+b.y;
}
return *this;
}
vector2 vector2::operator-(const vector2& b)
{
vector2 temp;
temp.x=x-b.x;
temp.y=y-b.y;
return temp;
}
vector2& vector2::operator-=(const vector2& b)
{
if(this!=&b)
{
x=x-b.x;
y=y-b.y;
}
return *this;
}
float vector2::operator* (const vector2& b)
{
return (x*b.x+y*b.y);
}
vector2 vector2::operator* (const float& b)
{
vector2 temp;
temp.x=x*b;
temp.y=y*b;
return temp;
}
vector2& vector2::operator*= (const float& b)
{
x=x*b;
y=y*b;
return *this;
}
vector2 vector2::operator/ (const float& b)
{
vector2 temp;
temp.x=x/b;
temp.y=y/b;
return temp;
}
vector2& vector2::operator/= (const float& b)
{
x=x/b;
y=y/b;
return *this;
}
void vector2::normalize()
{
float dist = sqrt(x*x+y*y);
x/=dist;
y/=dist;
}
void vector2::normalize(const float& dist)
{
x/=dist;
y/=dist;
}
float vector2::length()
{
return sqrt(x*x+y*y);
}
//}
The biggest thing I'm worried about is assignment /= operators.
Is it fine, and do you have any recommendations of fixes?