Simple look at casting operator overload:
#include <iostream>
using namespace std;
class fun{
int _data;
char _char;
int* _data2;
public:
fun():_data(0){}
fun(int d):_data(d),_char('w'),_data2(0){}
fun(int d, char c):_data(d),_char(c),_data2(0){}
fun(int d, char c,int size):_data(d),_char(c){_data2 = new int[size];}
void show(){cout << "data is: " << _data << endl;
cout << "character is: "<< _char << endl;}
operator int(){cout << "inside int casting operator" << endl;//casting operator int()
return _data;}
operator char(){{cout << "inside char casting operator" << endl;//casting operator char()
return _char;}}
operator int*(){cout << "inside int* casting operator" << _data2<<endl;//casting operator int*()
return _data2;}
~fun(){
delete [] _data2;
}
};
int main (){
int x=20;
char c='d';
int* ptr(0);
fun a(5);
a.show();
x=(int)a;//calling int casting operator of class
cout << "x: " << x << endl;//output: x: 5
cout << endl;
fun stuff(10,'f',3);
stuff.show();
c = char(stuff);//calling char casting operator of class
cout << c << endl;//output: f
cout << "&ptr: " << ptr << endl;
cout << "size: " << sizeof(ptr) << endl;
ptr = (int*)stuff;//calling int* casting operator
cout << "&ptr: " << ptr << endl;//output &ptr: (same addess as _data2 in fun class)
cout << "size: " << sizeof(ptr) << endl;
delete [] ptr;
return 0;
}
//ps a little thanks to Mr. D'amico for telling me casting is a operator XD
No comments:
Post a Comment