Sunday, July 12, 2009

In C++: I am confused of how to write an = Operator function.?

I am wring a program using Dynamic DataTypes.





I need an = operator function...





How can I write this?

In C++: I am confused of how to write an = Operator function.?
When dealing with dynamic data types, or any structure, the use of the standard equal operator may not have the desired effect. For instance, it may simply set the second structure to point to the same memory location as the first. If what you want is a true copy, a deep copy, of the structure, you need to overload the = operator and tell it what '=' means to you when you assign one dynamic data type to another. You set up the operator overload function just as you would with any other. The name of the function is 'operator='.





For example, say you have a class called Array. You could overload the =operator by declaring the overloaded operator function





const Array %26amp;operator=( const Array %26amp; );





and then define it with





const Array %26amp;Array::operator=( const Array %26amp;right_side)


{


if ( %26amp;right_side != this ) // make sure not self-assignment


{


if ( size != right_side.size )


{ //resize this one to match


delete [] ptr; // an Array attribute


size = right_side.size;


ptr = new int [size];


}





/// here's where the deep copy comes in...


for ( int i = 0; i %26lt; size; i++ )


ptr[i] = right_side.ptr[i];


}





return *this;


}





If you had two Array objects, array1 and array2, you would then use this by simply saying





array2 = array1;





where array1 would be taken in as the argument to the overloaded operator= function (called right_side within the function; right -side referring to what side of the equal sign it's on and assigns the return pointer (*this) to array2. THus, you now have two unique data structures with exactly the same data but which may be manipulated independently of one another.
Reply:You mean something like this?





int increasebyten(int value)


{


return value + 10;


}





int myvalue = 10;


myvalue = increasebyten(myvalue)
Reply:If you are assigning a value, use:





int value=0;





(int declares the datatype.)





Use = in conditional statements:





if(value == 1) // if the value = 1


{


}
Reply:This function has to take one parameter as a reference of the current class' type. You should check if the argument that is passed in is the same object, and if it is to return the current object.





This function has to manipulate the current object to make it equal to the object that was passed in as an argument. Then return the object after it has been made equal. This is to allow chaining of the operator.


No comments:

Post a Comment