Operator overload: Convert string type to integer. : Cast « Overload « C++






Operator overload: Convert string type to integer.

Operator overload: Convert string type to integer.

#include <iostream>
#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;
}


           
       








Related examples in the same category

1.Converter operatorConverter operator