yes,but..

Björn Lindberg d95-bli at nada.kth.se
Tue Aug 10 04:50:07 PDT 2004


michael <michael8110 at terra.com.br> writes:

> Thanks,guys,now
> #include<iostream>
>   using namespace std;
>   class car
>   {public:
>   car();
>   char itsName[20];
>   car(char * a)
>   { strcpy(itsName, a); }
>   };
>   int main()
>   {car citroen("DS19");
>    cout<<citroen.itsName<<"\n";
>   return 0;
>   }
> and
> 
> #include<string>
> #include<iostream>
>   using namespace std;
>   class car
>   {public:
>   string itsName;
>   car(string a)
>   {itsName=a;}
>   };
> 
>   int main()
>   {car citroen("DS19");
>   cout<<citroen.itsName<<"\n";
>   return 0;
>   }
> 
> do exactly the same thing,but  still i'd like to mention what was at
> the  origin of all this,namely what this code produces:
> #include<iostream>
> using namespace std;
> int main()
> {int arr[3]={1,2};
> cout <<arr<<"\n";
> char ar[3]={'b','y'};
> cout <<ar<<"\n";/*you are still trying to use a char *
> (memory address) as a value to assign to an array, which is NOT allowed
> in C.*/
> return 0;
> }
> which is
>    michael ~ # ./a.out
> 0xbffff750
> by
>   so,after all ar is not an char* but a char[] ,(although arr is an
> int*  )at least as seen by the compiler.Strange,isn't it?Maybe i'm
> making a  salad out of it all,anyway,at least now it works :-)

Patrick explained what is happening. The << operator is overloaded for
output streams, and it has many overloaded versions, where the type of
the argument is different. Here is an excerpt from the iostream header
on my system:

    ostream& operator<<(char c);
    ostream& operator<<(unsigned char c) { return (*this) << (char)c; }
    ostream& operator<<(signed char c) { return (*this) << (char)c; }
    ostream& operator<<(const char *s);
    ostream& operator<<(const unsigned char *s)
        { return (*this) << (const char*)s; }
    ostream& operator<<(const signed char *s)
        { return (*this) << (const char*)s; }
    ostream& operator<<(const void *p);
    ostream& operator<<(int n);
    ostream& operator<<(unsigned int n);
    ostream& operator<<(long n);
    ostream& operator<<(unsigned long n);
    [...]

C++ has stricter type checking than C, and the only reason that it
allows assigning a constant string (of type 'const char[]') to
'char *' is for backwards compatibility with C.

I found a tutorial on the net which discusses some of the differences
between pointers and arrays. perhaps it is helpful:

  http://www.gamespp.com/cprogramming/TutorialOnPointersAndArrays06.html


Björn



More information about the lfs-chat mailing list