标签:style blog class code java c
类型转换函数能够实现把一个类 类型 转换成 基本数据类型(int、float、double、char等) 或者 另一个类 类型。
其定义形式如下,注意不能有返回值,不能有参数,只能返回要转换的数据类型。
class X { public: operator TYPE() { //..... return TYPE对象; } };
例子:将一个类转换成基本数据类型和 类类型
#include <iostream> using namespace std; class Base { public: Base(int d):data(d){} void display(void){cout<<data<<endl;} private: int data; }; class DataCollection { public: DataCollection(char c, int in, float f, double d, Base s):ch(c),i(in),ft(f),db(d),bs(s){} //Data Cast operator char(){return ch;} operator int(){return i;} operator float(){return ft;} operator double(){return db;} operator Base(){return bs;} private: char ch; int i; float ft; double db; Base bs; }; int main(void) { Base bs1(5),bs2(100);bs2.display(); DataCollection dc(‘A‘,1,2.1f,3.1,bs1); char ch = dc; cout << ch << endl; int i = dc; cout << i << endl; float ft = dc; cout << ft << endl; double db = dc; cout << db << endl; bs2 = dc; bs2.display(); return 0; }
标签:style blog class code java c
原文地址:http://www.cnblogs.com/LubinLew/p/CppOperatorOverload-TypeCast.html