在C ++中从用户定义类型到原始类型的隐式转换

编程入门 行业动态 更新时间:2024-10-14 22:20:43
本文介绍了在C ++中从用户定义类型到原始类型的隐式转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我能够找到很多有关从隐式转换(例如,从int到用户定义类型)的信息.即,如果构造函数将int作为其参数,并且未以显式"作为前缀,则可能会发生隐式转换.

I am able to find plenty of information about implicit conversion from, say, an int to a user defined type. i.e. if a constructor takes an int as its parameter and is not prefaced by "explicit" then implicit conversions can occur.

如果我希望我的班级将隐式转换为一个整数怎么办?

What if I want my class to implicitly convert to an int?

例如,需要在SimpleClass的内部或外部添加什么函数,以便主函数可以编译并向控制台输出"1"?(请参阅评论)

For example, what function needs to be added either inside or outside of SimpleClass such that the main function will compile and output "1" to the console? (see comments)

#include <iostream> class SimpleClass { private: int m_int; public: SimpleClass(int value) : m_int(value) {} }; int main(int argc, const char * argv[]) { SimpleClass simpleclass(1); int i = simpleclass; // does not complile std::cout << i << std::endl; // should output "1" to the console return 0; }

推荐答案

隐式转换可以通过两种方式定义:

Implicit conversions can be defined in two ways:

  • 非显式单参数构造函数.
  • 非显式转换函数(又称转换运算符),N3337 12.3.2

后面的代码允许定义从类类型到原始类型的转换.只需添加

The later allows defining conversion from class type to primitive type. Just add

class SimpleClass { // ... operator int() const; }; SimpleClass::operator int() const { return m_int; }

更多推荐

在C ++中从用户定义类型到原始类型的隐式转换

本文发布于:2023-07-14 10:12:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1104069.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型   原始   定义   用户   隐式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!