Operator Help Please

This is a discussion on Operator Help Please within the C++ Programming forums, part of the General Programming Boards category; I am trying to over load the insertion operator to work with a class. I want to use get() to ...

  1. #1
    Still A Registered User DISGUISED's Avatar
    Join Date
    Aug 2001
    Posts
    499

    Question Operator Help Please

    I am trying to over load the insertion operator to work with a class. I want to use get() to load a character array inside the operator but I am having trouble. Here is a simple example to illustrate what I am trying to do in a larger program.
    Code:
     
    #include <iostream.h>
    const int MAX = 30; 
    class Person 
    { 
    private: 
    	int age; 
    	char gender; 
                    char name[MAX]; 
    public: 
    	friend istream& operator >> (istream&, Person&);
    	friend ostream& operator << (ostream&, Person&);
    }; 
    istream& operator >> (istream& in, Person& x) 
    { 
    	cout <<"\nEnter Age:";    in >> x.age; 
    	cout <<"\nEnter Gender:"; in >> x.gender; 
    	cout <<"\nEnter Name:";   cin.ignore(); x.cin.get(name,MAX);
    	return in;} 
    ostream& operator << (ostream& out, Person& x) 
    { 
    	cout << "\nAGE:";    out << x.age; 
    	cout << "\nGENDER:"; out << x.gender; 	
    	cout << "\nNAME:";   out << x.name;
    	return out;} 
    int main() 
    { 
    	Person p; 
    	cin >> p; 
    	cout << p; 
    	return 0; 
    }
    I have tried this a few different ways, but obviously cin is not a member of Person so that's pretty much my problem. Am I just going to have write a member function to load this array or is there any other way around this. Thanks. MSVC++6.0
    Last edited by DISGUISED; 03-29-2002 at 03:02 PM.

  2. #2
    S­énior Member
    Join Date
    Jan 2002
    Posts
    982
    If your operator>> function is taking a reference to an istream, shouldn't it use that istream all the way through? Same for the reference to Person.

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21