• ### Announcements

#### Archived

This topic is now archived and is closed to further replies.

# self conversion

## Recommended Posts

disjunction    122
hi i know u can write a conversion operator so that your class can be assigned to floats and things. but how can u write an operator to do the oposite, and assign your class to a float, without having an explicit method, like cfloat? float f = myclass;

##### Share on other sites
Fruny    1658
class A{   operator float() const { ... };};

[Questions (STFW) | GDNet Start Here | GDNet Search | Forum FAQ | Google | Asking Smart Questions ]
[Docs (RTFM) | MSDN | SGI''s STL | OpenGL | File formats]
[C++ Must Haves (RTFS) | MinGW | Boost | Loki | FLTK | SDL ]

Stolen from Magmai Kai Holmlor, who held it from Oluseyi, who was inspired by Kylotan...

##### Share on other sites
disjunction    122
how would that work, fruny? there isnt a return value.
wouldnt you need one?

float f = myclass;

i need something like this:

float& operator float()
{
return (float)_me;
}

but, that doesnt compile.

##### Share on other sites
Dactylos    122
quote:
Original post by disjunction
how would that work, fruny? there isnt a return value.
wouldnt you need one?

float f = myclass;

i need something like this:

float& operator float()
{
return (float)_me;
}

but, that doesnt compile.

If you want to write a conversion to float& you should call it 'operator float&', not 'operator float'. The return type can not be specified, it is always the same as the 'name' of the conversion operator.

An example:

    class Foo{   float myValue; public:   Foo(float value) : myValue(value)   {   }    // Convert Foo to float&   operator float& ()   {      return myValue;   }}; int main(int, char**){   Foo foo(5.0f);   float x = foo;   printf("x = %f\n", x);   printf("(float)Foo = %f", (float)Foo);      // The explicit cast here is required      // because printf takes a variable number      // of arguments, and the compiler won't      // coerce any types automatically      // (since it has no way of knowing that      // it should coerce the type Foo to float).}

(The above code is untested, and so may not be completely correct, but hopefully you get the idea)

[edited by - Dactylos on May 2, 2002 12:42:59 AM]

##### Share on other sites
Guest Anonymous Poster
think about it, why would you need to specify a return type? Afterall the function is written solely to convert to a type. Thus they decided to leave off the return type entirely. Kind of weird but maybe it is to make it so that you can''t pull tricks like specifying the return type incorrectly.