问题
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