Get premium membership and access questions with answers, video lessons as well as revision papers.

Overload the coord class so it can use coord object in operations in which an integer value can be multiplied by each coordinate. Allow the...

      

Overload the coord class so it can use coord object in operations in which an integer value can be multiplied by each coordinate. Allow the operations to use either order:
ob * int or int * ob.

  

Answers


Davis

//Overload the * for ob*int and int*ob.
#include
using namespace std;
class coord {
int x, y; /coordinate values
public:
coord() {x=0; y=0;}
coord(int i, int j) {x=i; y=j;}
void get_xy(int &i, int &j) {i=x; j=y;}
friend coord operator*(ob1, int i);
friend coord operator * (int i, coord ob2);
};
//Overload * one way
coord operator*(coord ob1, int i)
{
coord temp;
temp.x = ob1.x * i;
mp.y = ob1.y * i;
return temp;
}
// Overload * another way.
coord operator *(int i, coord ob2)
{
coord temp;
temp.x = ob2.x * i;
temp.y = ob2.y * ireturn temp;
}
int main()
{
coord o1(10, 10) o2;
int x, y;
o2 = o1 * 2; //ob * int
o2.get_xy(x, y);
cout << "(o1*2) x:" << x <<" y: << y << "\n"; = 3 * o1; //int * ob
o2.get_xy(x, y);
cout << "(3*o1) x: "<< x <<" y: "<< y <<"\n";
return 0;
}

Githiari answered the question on June 8, 2018 at 18:40


Next: Overload the -- operator for the coord class. Create its both prefix and postfix forms
Previous: Using a friend, show how to overload the -- relave to the coord class. Define both the prefix and postfix forms.

View More Computer Science Questions and Answers | Return to Questions Index


Learn High School English on YouTube

Related Questions