:
This message was edited by Donotalo at 2005-9-29 4:4:53
: :
I think this syntax would more logical: int operator(), double operator(), but it is not allowed.
:
: I agree with this. even if there is no return statement inside conversion function body, no error generated!
:
: now i know that conversion functions can be made const. i asked why it is not possible, because, my main program is much more different that this simple program. const conversion functions weren't allowed there, whereas it is allowed in this example. but here is a new problem:
:
: #include <iostream>
: using namespace std;
:
: class Ratio {
: int den, num;
: public:
: Ratio(int n = 0, int d = 1): den(d), num(n) {}
: operator double() const {return (double(den)/double(num));}
: operator int() {return den/num;}
: };
:
: int main()
: {
: Ratio r(29, 15);
: int i = r;
: double d = r;
:
: cout << i << endl << d << endl;
: return 0;
: }
:
: Output: 0, new line, 0. why?? compiler VC++ 6.
:
:
GCC gives a warning for it: "choosing operator int() because conversion sequence for the argument is better". It obviously chooses int-operator, probably because the object used when calling isn't const. If you put both operators to const, it will take the double one.
It is probably because of priority with function overloading. If you have two member functions with the same name, like:
void hello() const
{
cout << "const";
}
void hello()
{
cout << "not const";
}
It will pick one depending on the type of the object.
If the object isn't const, it will take the second one.
If the object is const, only the first one makes sence.