C++/Overload/Cast

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

Converter operator

<source lang="cpp">

  1. include <iostream>

using namespace std; class Power {

 double b;
 int e;
 double val;

public:

 Power(double base, int exp);
 Power operator+(Power o) {
   double base;
   int exp;
   base = b + o.b;
   exp = e + o.e;
   Power temp(base, exp);
   return temp;
 }
 operator double() { // convert to double
    return val; 
 } 

}; Power::Power(double base, int exp) {

 b = base;
 e = exp;
 val = 1;
 if(exp == 0) 
    return;
 for( ; exp>0; exp--) 
    val = val * b;

} int main() {

 Power x(4.022, 2);
 double a;
 a = x;             // convert to double
 cout << x + 100.2; // convert x to double and add 100.2
 cout << endl;
 Power y(32.3, 3), z(0, 0);
 z = x + y;         // no conversion
 a = z;             // convert to double
 cout << a;
 return 0;

}

      </source>


Operator overload: Convert string type to integer.

<source lang="cpp">

  1. include <iostream>
  2. include <cstring>

using namespace std; class StringClass {

 char str[80];
 int len;

public:

 StringClass(char *s) { 
    strcpy(str, s); 
    len = strlen(s); 
 }
 operator char *() { 
    return str; 
 }
 operator int() { 
    return len; 
 }

}; int main() {

 StringClass s("Conversion functions are convenient.");
 char *p;
 int l;
 l = s; // convert s to integer - which is length of string
 p = s; // convert s to char * - which is pointer to string
 cout << "The string:\n";
 cout << p << "\nis " << l << " chars long.\n";
 return 0;

}


      </source>