类型转换

孤街醉人 提交于 2019-12-18 01:35:49

一、自定义类型转基本类型

如果想把自定义类型转为基本类型,则需要重载类型转换符,否则就会报错,无法完成转换。

class TypeTest
{
public:
    TypeTest()
    {
        int_type = 0;
        double_type = 0.0;
    }

    operator int() const //重载int
    {
        return int_type;
    }

    operator double() const //重载double
    {
        return double_type;
    }

private:
    int int_type = 0;
    double double_type = 0;
};

int main()
{
    TypeTest t1;

    int t2 = (int)t1;
    
    cout << t2 << endl;
    return 0;
}

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!