Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    New to the CF scene
    Join Date
    Feb 2011
    Location
    San Antonio, Tx
    Posts
    6
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Classes and Strings

    Having a problem with classes and strings and pointers.

    Code:
    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

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

    Can someone explain what i am doing wrong?
    Thank You

  • #2
    Regular Coder
    Join Date
    Jun 2007
    Location
    USA
    Posts
    527
    Thanks
    26
    Thanked 74 Times in 72 Posts
    You need to take the address of the string using the & operator:
    Code:
    return &fname;
    For all types T, T and T* are different types.
    Trinithis

  • #3
    Regular Coder
    Join Date
    Sep 2011
    Posts
    103
    Thanks
    0
    Thanked 14 Times in 14 Posts
    Quote Originally Posted by cgarza View Post
    Having a problem with classes and strings and pointers.

    Code:
    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

    Code:
    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);
    }

  • #4
    Regular Coder
    Join Date
    Sep 2011
    Posts
    103
    Thanks
    0
    Thanked 14 Times in 14 Posts
    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);
    }


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •