Programming and Graphics

(Kiana) #1

170 Introduction to C++ Programming and Graphics


Problems


6.8.1.A point in the plane defines a vector starting at the origin,x=0,y=0,
and ending at that point. Add to the algebra class a member function
that rotates the vector by a specified angle around thezaxis.


6.8.2.Add to the algebra class a member function that implements subtrac-
tion, a second function that implements multiplication, and a third mem-
ber function that implements division.


6.9 Operator overloading.........................


In the main function of the algebra code, we may add a point A to another
point B to produce the new point C using the following statements:


algebra save = A; // save A
A.shift(B.get(chroma)); // shift A
algebra C=A; // C is the shifted A
A=save; // reinstate A

Alternatively, we can directly add points A and B by overloading the +
operator. This is done by defining the algebra class addition function:


algebra algebra::operator + (algebra patespani)
{
algebra add;
add.x = x+patespani.x;
add.color = setcolor(add.x);
return add;
}

and then inserting the following declaration in the public section of the class:


algebra operator + (algebra);

Once this is done, we can state in the main program:


C=A+B;

which adds the two points A and B by adding the correspondingxvalues and
calculating the new color to produce a point C.


Table 6.9.1 displays operators that can be overloaded in C++. Because
the left-to-right copy assignment operator (=) is overloaded by default, it is
declared and implemented only if a special functionality is desired. Tables 6.9.2
and 3 explain the syntax of common overloading declarations. Class overloading

Free download pdf