C++/Overload/Return Operator

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

Operator as return type

<source lang="cpp">

  1. include <iostream>

using namespace std; int p(int base, int exp); class Power {

 int base;
 int exp;

public:

 Power(int b, int e) { 
    base = b; exp = e; 
 }
 operator int() { 
    return p(base, exp); 
 }

}; // Return base to the exp power. int p(int base, int exp) {

 int temp;
 for(temp=1; exp; exp--) 
    temp = temp * base;
 return temp;

}

int main()

{

 Power object1(2, 3), object2(3, 3);
 int result;
 result = object1;
 cout << result << "\n";
 result = object2;
 cout << result << "\n";
 cout << object1 + 100 << "\n";
 return 0;

}


      </source>