zoukankan      html  css  js  c++  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;
    }
  • 相关阅读:
    MySQL基础(一):检索数据
    Go基础(九):并发
    Go基础(八):反射
    Go基础(七):接口
    Go基础(六):方法
    Go基础(五):结构体
    Go基础(四):流程控制和函数
    Go基础(三):内置基础类型和一些技巧
    Go基础(二):变量和常量
    Go基础(一):命令行操作
  • 原文地址:https://www.cnblogs.com/LubinLew/p/CppOperatorOverload-TypeCast.html
Copyright © 2011-2022 走看看