Click to See Complete Forum and Search --> : C++ = operator; vector math
if I have
class obj
{
double x;
double y;
}
can I do something like
obj instance;
instance = { 1.0, 2.0 };
assign the numbers to x and y? I don't think you can do this, but I remember seeing something like this somewhere.
Energon
07-10-2002, 09:02 AM
I don't think you can do that, but that's okay because you can just define a constructor:
obj::obj(double x, double y) : m_x(x), m_y(y)
{
}
and then do a
obj instance(1.0, 2.0);
or
instance = obj(1.0, 2.0);
Stuka
07-10-2002, 09:30 AM
I've never tried that with objects - however, in the declaration you give, it COULDN'T work, because both data members are private, and so you can't access them directly (which is what you'd be doing). I do know, however, that if that was a struct declaration, it should work, since that's a valid C construct, and as we all know, C++ compilers are required to compile valid C constructs that don't violate any C++ rules, which a struct declaration there wouldn't.
knavely
07-14-2002, 01:41 PM
"I've never tried that with objects - however, in the declaration you give, it COULDN'T work, because both data members are private, and so you can't access them directly (which is what you'd be doing)."
well the thing is you sort of can do this by overloading the = operator.
but the problem i see is, how do you indicate that your argument is of the form { int int } ? now by no means do i mean to imply that its not possable, i just dont know, and i am extreamly curious.
you could do it with an array quite easily or another object(sorry if you already knew this, kinda seemed like what you might be asking).
object &operator=(double array[])
{
x = array[0];
y = array[1];
return *this;
}
or with another object:
object &operator=(object &A)
{
if(this != &A)//make sure we dont assign to ourself
{
x = A.x;
y = A.y;
}
else...
return *this;
}
but with something like {1.0, 2.0 } for all i know it might be possable, but what definition to use???:confused:
knavely
07-14-2002, 01:50 PM
woops forgot implementation
:o
o yes and of course, after you have overloaded the = operator in the ways i just mentioned you can do:
double array[2] = {1,2};
object instance = array;
or if you have an object initialez like:
object instanceA(1,2), instanceB;
you can do:
instanceB = instanceA;