How does conversion operator return a value?

我的未来我决定 提交于 2019-12-18 18:51:24

问题


For a class A, an integer conversion operator would look something like;

operator int() //Here we don't specify any return type
{
    return intValue;
}

How is the above function able to return a value when its return value type appears not to be specified? It doesn't appear to return "anything", but I know it's not void.

How is this meaningful when a return type is not specified?


回答1:


The return type of operator T() is always T. It's a special case of C++.

It does not use standard function prototype syntax T foo() because 2 functions with the same name differing only by the return type cannot coexist (e.g. int foo() conflicts with double foo()). If this syntax is used then you can only define 1 conversion operator overload, which is undesirable.




回答2:


The return value of operator T() where T is a type is always T.




回答3:


The name of the conversion operator is its type. If this were not the case, you could define an int conversion operator (for example) that actually returned a double. A somewhat similar line of thinking applies to constructors, which also do not have a return type.



来源:https://stackoverflow.com/questions/2036923/how-does-conversion-operator-return-a-value

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