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;
}

 

posted @ 2014-05-10 12:25  LubinLew  阅读(4773)  评论(0编辑  收藏  举报