Path: utzoo!attcan!uunet!microsoft!jimad From: jimad@microsoft.UUCP (Jim ADCOCK) Newsgroups: comp.lang.c++ Subject: Re: conversions Message-ID: <54073@microsoft.UUCP> Date: 13 Apr 90 17:14:10 GMT References: <7633@cadillac.CAD.MCC.COM> Reply-To: jimad@microsoft.UUCP (Jim ADCOCK) Organization: Microsoft Corp., Redmond WA Lines: 71 In article <7633@cadillac.CAD.MCC.COM| vaughan@puma.cad.mcc.com (Paul Vaughan) writes: | |The following program compiles cleanly under g++-1.37.1, but gets |three errors under cfront (Sun CC, actually). | |--------------------------- |class Int { | int i; |public: | Int(int j) : i(j) {} | Int(Int& I) { i = I.i; } | operator int() { return i; } | operator int&() { return i; } |}; | |main() { | Int i = 4; | i += i; // line 29 |} | |------------------------ |CC -c convert.cc |CC convert.cc: |"convert.cc", line 30: error: ambiguous conversion of Int |"convert.cc", line 30: error: ambiguous conversion of Int |"convert.cc", line 30: error: bad operand types Int Int for += |3 errors | |Any comments on why CC generates these errors, and whether or not this |is the right thing to do? I realize that a class that works Exactly |like an int for both reading and assignment probably isn't very |useful, but should I be able to do it this way? See Hansen "The C++ Answer Book" pg 251, etc. My question would be why g++ accepts this program? To do so surely represents an extension to the language. I would guess this might be because g++ interprets x += y as x = x + y and counts on the optimizer to keep x from being evaluated more than once? --- Given that += is not overloaded in Int, the += referred to must be of the form int x += int y. How then does the compiler make the int x out of an Int i? There are two ways: Use operator int or use operator int&. The disambiguating rules of C++ do not say which operator to use, therefor the left hand side "x" is ambiguous. How does the compiler make the int y out of an Int i? There are two ways: Use operator int or use operator int&. The disambiguating rules of C++ do not say which operator to use, therefor the right hand side "y" is ambiguous. So we cannot do the conversions. Is there then a += we can use given an Int += Int ? No. --- Please note that Hanson's comments about not being able to differentiate pre and post inc and dec have been superceeded by popular demand -- to differentiate declare: operator++() // prefix ++a operator++(int); // postfix a++ -- assuming you have a very recent release compiler that actually supports this hack. [ This according to the illuminated bible section 13.4.7 ]