c++ - Specific things with type cast operator -


#include <iostream> using namespace std;  struct {     a(int a):a(a){}     int a; };  struct b {     operator a()     {         return 10;     } };  int main() {     b b;     cout << ((a)b).a << endl;     return 0; } 

this code compiles , prints 10 in visual studio. in wikipedia next cast operator found sentence: note: user-defined conversions, return type implicitly and necessarily matches operator name.

now how code above works? feature of visual studio? or shoud match implicitly?

operator a() user-defined conversion operator. it's job return a by-value when cast b a.

your operator a() function returning literal integer value, 10. operator a needs return a, a's convert constructor called value 10. results in temporary a being constructed. accessing .a on temporary object, , inserting value of .a in stream, results in seeing 10 on screen.

edit

when wiki said converstion operator "implicitly" returned a, meant don't have specify return type in function declarion. it's a , there's nothing can it.

when wiki said "necesarrily" returned a meant can't return a. can't return convertible a. has return a exactly.


Comments

Popular posts from this blog

objective c - Change font of selected text in UITextView -

php - Accessing POST data in Facebook cavas app -

c# - Getting control value when switching a view as part of a multiview -