我能够找到很多有关从隐式转换(例如,从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 ++中从用户定义类型到原始类型的隐式转换
发布评论