On 3¿ù26ÀÏ, ¿ÀÀü5½Ã31ºÐ, blargg....@gishpuppy.com (blargg) wrote:
> Juha Nieminen wrote:
> > ljh131 wrote:
> > > but i want to know why exactly c++ prohibits this casting. someone say
> > > array should be considered as 'const pointer'.
>
> > I assume you know the difference between "const pointer" and "pointer
> > to const".
>
> > The latter is a pointer variable, which has been declared to point to
> > a value which cannot be modified through that pointer (ie. the pointer
> > points to a const).
>
> > The former means that the pointer variable itself is const (rather
> > than the value it's pointing to). In other words, you cannot modify the
> > pointer itself to point somewhere else.
>
> > You can get a long way by, indeed, thinking that array names act like
> > const pointers (ie. pointer variables which cannot be changed).
>
> [...]
>
> You can get all the way by simply noting that an array can be implicitly
> converted into a pointer to its first element, similar to how a double can
> be implicitly converted into an int. In both cases, you can't take a
> non-const reference to this implicit conversion:
>
> // using int and double
> typedef double T;
> typedef int U;
> void f( U& );
> void fc( U const& );
>
> T t;
> void example()
> {
> f( t ); // error
> fc( t ); // OK, creates temporary
>
> U const& temp = t; // equivalent to previous statement
> fc( temp );
> }
>
> // using array
> typedef int T [2];
> typedef int* U;
> void f( U& );
> void fc( U const& );
>
> T t;
> void example()
> {
> f( t ); // error
> fc( t ); // OK, creates temporary
>
> U const& temp = t; // equivalent to previous statement
> fc( temp );
> }
>
> The code after the typedefs is identical in both cases.
thanks for all of your answers.
|