C++ 重载类型转换符

/// @file 1.cpp
/// @brief 
/// @author EastonWoo 
/// 0.01
/// @date 2015-05-20


#include "stdio.h"


class Vec2{
public:
    Vec2(int x, int y){
        m_ix = x;
        m_iy = y;
    }

    int m_ix;
    int m_iy;
};

class Size{
public:
    Size(int w, int h){
        m_iWidth = w;
        m_iHeight = h;
    }

    operator Vec2(){
        return Vec2(m_iWidth, m_iHeight);   // 重载类型转换符 相当于 (Vec2)this ;
    }

    operator int(){                         // 重载类型转换符 相当于 (int)this ;
        return 99;
    }

    int m_iWidth;
    int m_iHeight;
};

int main(int argc, const char *argv[])
{

    Size s = Size(10,20);

    Vec2 v = s;

    printf("%d, %d\n", v.m_ix, v.m_iy);

    int i = s;

    printf("%d\n", i);
    
    return 0;
}



tmp-> g++ 1.cpp && ./a.out
10, 20
99
tmp->

你可能感兴趣的:(C++,重载类型转换符)