...

View Full Version : Classes and Strings



cgarza
11-01-2011, 03:56 AM
Having a problem with classes and strings and pointers.



class Person
{
protected:
string fname;
public:
string* get_fname();
void set_fname();
friend std::istream& operator >> (std::istream&, Person&);
friend std::ostream& operator<<(std::ostream&, Person&);
};
string* Person::get_fname()
{
return(fname);
}
int main()
{

Student S1 = new Student;
S1 -> set_fname();
S1 ->get_fname();

return(0);
}

I compile and I get the error


cannot convert "Person::fname' from type 'string' to type 'string *'


Can someone explain what i am doing wrong?
Thank You

Trinithis
11-03-2011, 12:44 AM
You need to take the address of the string using the & operator:


return &fname;


For all types T, T and T* are different types.

jassi.singh
11-09-2011, 07:22 AM
Having a problem with classes and strings and pointers.



class Person
{
protected:
string fname;
public:
string* get_fname();
void set_fname();
friend std::istream& operator >> (std::istream&, Person&);
friend std::ostream& operator<<(std::ostream&, Person&);
};
string* Person::get_fname()
{
return(fname);
}
int main()
{

Student S1 = new Student;
S1 -> set_fname();
S1 ->get_fname();

return(0);
}

I compile and I get the error


cannot convert "Person::fname' from type 'string' to type 'string *'


Can someone explain what i am doing wrong?
Thank You

Hello,

Use this

string* Person::get_fname()
{
return(&fname);
}

jassi.singh
11-09-2011, 07:33 AM
Hi,


Either declare
protected:
string fname;

as

protected:
string* fname;

or

write

string* Person::get_fname()
{
return(fname);
}

as

string* Person::get_fname()
{
return(&fname);
}



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum