Hi,
--
Regards, Ron AF Greve
http://moonlit.xs4all.nl
"James" <james@hotmail.com> wrote in message
news:uqy3f.234$CI.124@newsfe2-gui.ntli.net...[color=blue]
> How do you pass a string into a function and set the contents of an
> internal string field to be the contents of the string passed into the Set
> method?
>
> My attempt at doing this below doesn't work and produces errors such as
> "class 'User' has an illegal zero-sized array" and "'=' : cannot convert
> from 'char[]' to char[]'".
>
>
>
> /* User.h */
> class User
> {
> public:
> void SetUserID(int u);[/color]
------> void SetName(char *n);[color=blue]
>
> private:
> int user_id;[/color]
------> char *name;[color=blue]
> };
> /* END CLASS DEFINITION User */
> #endif /* __USER__ */
>
>
> /* User.cpp */
> #include "User.h"
>
> void User::SetUserID(int u)
> {
> user_id = u;
> }[/color]
//> void User::SetName(char n[])
------>void User::SetName(char *n)
[color=blue]
> {
> name = n;
> }
>
>
>[/color]
Just pass a pointer to char. However be careful with above code since 'name'
now points to the same memory as the pointer you passed in your routine. You
are more likely to want to do the following:
void User::SetName(char *n)
{
// Delete any possibly previously allocated name or do nothing if name is
0
delete[] name;
name = new char[ strlen( n ) + 1 ];
strcpy( name, n );
// DON' T forget to add delete[] name in the destructor and initialize
name with 0 in the constructor
}
Or what I prefer just use the STL string class
#include <string>
using namespace std;
void User::SetName( const string& Name )
{
this->name = Name;
}
Regards, Ron AF Greve[color=blue]
> P.S. How do you re-initialise an object e.g. in Java it's "new
> ObjectName()", what's the C++ syntax?
>[/color]