C++/Overload/Product

Материал из C\C++ эксперт
Перейти к: навигация, поиск

Overload the "*" for "ob * int" and "int * ob".

<source lang="cpp">

  1. include <iostream>

using namespace std; class MyClass {

 int x, y; 

public:

 MyClass() { 
    x=0; 
    y=0; 
 }
 MyClass(int i, int j) { 
    x=i; 
    y=j; 
 }
 void getXY(int &i, int &j) { 
    i=x; 
    j=y; 
 }
 friend MyClass operator*(MyClass object1, int i);
 friend MyClass operator*(int i, MyClass object2);

}; // Overload * one way. MyClass operator*(MyClass object1, int i) {

 MyClass temp;
 temp.x = object1.x * i;
 temp.y = object1.y * i;
 return temp;

} // Overload * another way. MyClass operator*(int i, MyClass object2) {

 MyClass temp;
 temp.x = object2.x * i;
 temp.y = object2.y * i;
 return temp;

} int main() {

 MyClass object1(10, 10), object2;
 int x, y;

 object2 = object1 * 2;  // ob * int
 object2.getXY(x, y);
 cout << "(object1*2) X: " << x << ", Y: " << y << endl;
 object2 = 3 * object1; // int * ob
 object2.getXY(x, y);
 cout << "(3*object1) X: " << x << ", Y: " << y << endl;
 return 0;

}


      </source>