c – 从自定义类转换为内置类型

c – 从自定义类转换为内置类型,第1张

概述为了清楚起见,让我的新课程成为: class MyInt{ public: MyInt(int x){theInt = x /10;} int operator+(int x){return 10 * theInt + x;} private int theInt; }; 让我们说我希望能够定义: MyInt Three(30); i 为了清楚起见,让我的新课程成为:
class MyInt{    public:       MyInt(int x){theInt = x /10;}       int operator+(int x){return 10 * theInt + x;}     private       int theInt; };

让我们说我希望能够定义:

MyInt Three(30); int thirty = Three;

但是为了得到这个结果,我写道:

MyInt Three(30); int thirty = Three + 0;

如何从我的Custom类自动转换为内置类型

解决方法 具有类型转换功能:
class MyInt{    public:       MyInt(int x){theInt = x /10;}       int operator+(int x){return 10 * theInt + x;}       operator int() const { return theInt; } // <--    private       int theInt; };
总结

以上是内存溢出为你收集整理的c – 从自定义类转换为内置类型全部内容,希望文章能够帮你解决c – 从自定义类转换为内置类型所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1237906.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-06
下一篇 2022-06-06

发表评论

登录后才能评论

评论列表(0条)

保存