在C ++中从用户定义类型到原始类型的隐式转换 [英] Implicit conversion from user-defined type to primitive type in C++

查看:55
本文介绍了在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 ++中从用户定义类型到原始类型的隐式转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆