C++/Class/conversion Function
A simple conversion function example.
#include <iostream>
using namespace std;
class MyClass {
int x, y;
public:
MyClass(int i, int j) {
x = i;
y = j;
}
operator int() {
return x*y;
}
};
int main()
{
MyClass object1(2, 3), object2(4, 3);
int i;
i = object1; // automatically convert to integer
cout << i << "\n";
i = 100 + object2; // convert object2 to integer
cout << i << "\n";
return 0;
}
Convert to char * in function call
#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 *() { // convert to char*
return str;
}
};
int main()
{
StringClass s("This is a test\n");
char *p, s2[80];
p = s; // convert to char *
cout << "Here is string: " << p << "\n";
strcpy(s2, s);
cout << "Here is copy of string: " << s2 << "\n";
return 0;
}