![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Professional Programmer
|
Operator Overloading issue [solved]
Hey all, trying to do some operator overloading on a Vector class (school, you know how it goes). And for some reason my operator= method won't actually assign the new value. Let me print some related code.
//definition
class Vector {
float x,y,z;
public:
Vector();
Vector(float, float, float);
Vector(const Vector&);
Vector operator + (Vector);
Vector operator - (Vector);
Vector operator * (Vector);
Vector operator / (Vector);
Vector operator = (Vector);
Vector operator == (Vector);
Vector operator != (Vector);
Vector operator () (Vector);
float dot_product(Vector);
Vector cross_product(Vector);
float length();
float normalize();
void print_vector();
};
//two constructors used
Vector::Vector(const Vector &v)
{
x = v.x;
y = v.y;
z = v.z;
}
Vector::Vector(float new_x, float new_y, float new_z)
{
x = new_x;
y = new_y;
z = new_z;
}
//the operator= method
Vector Vector::operator= (Vector v)
{
Vector t (v.x, v.y, v.z);
t.print_vector();printf("\n");
return (t);
}
//main i've been using
int main()
{
Vector v (1, 2, 3);
Vector z (1, 2, 3);
Vector q;
v.print_vector(); printf("\n");
z.print_vector(); printf("\n");
q = z + v;
q.print_vector(); printf("\n");
}
//the output
jule@dolphy ~/classes/cs265/labs/lab1 $ ./vector
(1.000, 2.000, 3.000) //created vector v
(1.000, 2.000, 3.000) //created vector z
(2.000, 4.000, 6.000) //in operator+ method
(2.000, 4.000, 6.000) //in operator= method
(0.000, 0.000, 0.000) //q = v + z;Thanks in advance Dizz Last edited by Dizzutch; Jan 29th, 2005 at 8:46 AM. |
|
|
|
|
|
#2 |
|
Programmer
Join Date: Dec 2004
Posts: 35
Rep Power: 0
![]() |
Try this instead;
Vector& Vector::operator= (const Vector& v)
{
x = v.x;
y = v.y;
z = v.z;
return *this;
} |
|
|
|
|
|
#3 |
|
Professional Programmer
|
Ah, there we go, can you explain that real quick? I'm not sure how this method is different than mine.
|
|
|
|
|
|
#4 |
|
Professional Programmer
|
actually the signature Vector Vector::operator = (Vector v) works fine. no need for the &.
|
|
|
|
|
|
#5 |
|
Professional Programmer
|
nm, i think i see what you're doing. thanks!
|
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|