dan@dyndata.UUCP (Dan Everhart) (05/25/90)
Consider the following program:
class Index
{
public:
Index (int i) : v (i) {};
operator int () { return v; };
private:
int v;
};
Index x (0);
char ac [10];
f ()
{
ac [x] = 'a'; // this line fails
ac [(int) x] = 'a';
ac [int (x)] = 'a';
}
On the marked line, I expected the compiler to make an implicit
conversion of x to int, since the Index class has an operator int ()
function defined. Zortech 2.06 gives the error message:
"opint.cpp", line 17 Syntax error: illegal pointer arithmetic
Had: <near *><char>
and: <struct Index>
The subsequent two lines, with their explicit conversions, compile
fine.
Although I could not find any example in The C++ Primer of exactly
this nature, there is a close one on p. 283 where Lippman defines a
SmallInt class, with similar conversion operators and says, "A
SmallInt class object can now be used *anywhere* in int object can be
used." (Emphasis mine.)
Taking a clue from the error message, I also tried adding the line
friend char & operator + (char *, Index);
to the class definition, attempting to provide assistance with the
pointer arithmetic. It made no difference.
So, should this work?randolph@ektools.UUCP (Gary L. Randolph) (05/30/90)
In article <684@dyndata.UUCP> dan@dyndata.UUCP (Dan Everhart) writes:
#
#Consider the following program:
#
#class Index
# {
#public:
# Index (int i) : v (i) {};
# operator int () { return v; };
#private:
# int v;
# };
#
#Index x (0);
#char ac [10];
#
#f ()
# {
# ac [x] = 'a'; // this line fails
^^^^^^^^^^^^^^^It shouldn't
#
# ac [(int) x] = 'a';
# ac [int (x)] = 'a';
# }
#
#
#On the marked line, I expected the compiler to make an implicit
#conversion of x to int, since the Index class has an operator int ()
#function defined. Zortech 2.06 gives the error message:
Your expectation is valid!
#"opint.cpp", line 17 Syntax error: illegal pointer arithmetic
#Had: <near *><char>
#and: <struct Index>
#The subsequent two lines, with their explicit conversions, compile
#fine.
You should not have to cast!
#Although I could not find any example in The C++ Primer of exactly
#this nature, there is a close one on p. 283 where Lippman defines a
#SmallInt class, with similar conversion operators and says, "A
#SmallInt class object can now be used *anywhere* in int object can be
#used." (Emphasis mine.)
Lippman is correct.
#So, should this work?
Yes.
I have tested your code using Sun C++ 2.0 and all is as you had
hoped! (minor point: Obviously f() should be defined as a void function)
Garykimura@zuken.co.jp (Naoto Kimura) (05/31/90)
In article <2670@ektools.UUCP> randolph@ektools.UUCP (Gary L. Randolph) writes: > > #So, should this work? > > Yes. > I have tested your code using Sun C++ 2.0 and all is as you had > hoped! (minor point: Obviously f() should be defined as a void function) > I have tested using Glockenspiel C Preprocessor, release 1.2 E too and there was no problem but trivial warning. -- Kimura Naoto