Daniel Glenfield escribi=F3:
> My skills are shot.
>
> I am trying to create a quick program that has a class with a private
> member
> that is an employee's name, and one of the member functions (public)
> returns
> a pointer to that private member (it's an example of what not to do).
>
> The program's main function should go like this:
>
> Create a class object.
> Create a global pointer.
> Ask for user name.
> Call SetEmployeeName passing the object to it.
> Set the typed string to be the private member EmpName.
> Return to main.
> Call GetEmployeeName, passing the object to it.
> Assign the private member EmpName to the global pointer.
> Return the pointer to main.
> Show what the pointer is pointing at (for example cout<< *GlobalPointer
> <<
> endl;)
>
> any refinements would be great. Remember this is an example of what not
> to
> do (returning pointers to private members). I have trouble putting the
> string in to the object's data member, so I could do with some help!
>
Writing it would be a simple matter of cin inside the set function or pas=
s
the pointer of the string (I am assuming you want to use char*, however
writting C++ string would be the recommended way, and where you need
char*, you use the member function c_str() of string class)
The function for get the string should be something like this:
char *const function(parameters);
so you cannot modify it out of the class's functions.
Daniel Glenfield escribi=F3:
> This is the code currently
> String GetName() const;
>
> To make the function return a const string reference, do I changeit to
>
> String& GetName() const;
>
> or is it now returning a String object?
Before the answer to this, you write String, C++ is case sensitive, so if
you haven't defined a class String it will say String not defined.
Now let's go with the answer: With that you say GetName won't modify the
member inside it, but you'll will be able to modify the return value,
since it is not constant and it is what you need to be constant (the othe=
r
is recommended, of course)
You have to do
const string GetName() const;
This will not modify the member while it does its work and will return th=
e
result to a constant member which won't be modified, and which will have
no access to the member, since there will be a copy of it.
With the solution you propose, returning string&, you're returning a
reference to it, so if the caller modifies it, the member will be
modified, because we can say that returning a reference is the same than
returning a pointer, with the difference that you can treat it as if it
were not a pointer, and when you access it you will access the variable a=
t
that address of memory, so you will access to the member variable
directly.
|