yungman
- 5,741
- 294
I have a question about overloading << and >>. Below is my program.
The question is where is the correct way to put the body of the operator<<() and operator >>() codes.
I have seen both in the book and in videos they put the codes OUTSIDE of the class definition like in line 19 to 26 within the comment.
I tried putting inside the class Person in line 9-12 and line15 and it works. Is there a problem to put it inside the class declaration like in my program here?
Thanks
The question is where is the correct way to put the body of the operator<<() and operator >>() codes.
I have seen both in the book and in videos they put the codes OUTSIDE of the class definition like in line 19 to 26 within the comment.
I tried putting inside the class Person in line 9-12 and line15 and it works. Is there a problem to put it inside the class declaration like in my program here?
C++:
#include <iostream>
#include <string>
using namespace std;
class Person {
string name; int age;
public:
Person() { name = "Alan"; age = 0; }
friend ostream& operator <<(ostream& output, Person& p) {
output << " For whatever it's worth " << endl;
output << " my name is " << p.name << " and my age is " << p.age << "\n\n";
return output;
}
friend istream& operator >>(istream& input, Person& p) {
input >> p.name; input >> p.age; return input;
}
};
/*
ostream& operator << (ostream& output, Person& p) {
output << " For whatever it's worth " << endl;
output << " my name is " << p.name << " and my age is " << p.age << "\n\n";
return output;
}
istream& operator >>(istream& input, Person& p) {
input >> p.name; input >> p.age; return input;
}
*/
int main()
{
cout << " Enter the name and age " << endl;
Person per;
cin >> per;
cout << per << "\n\n";
return 0;
}
Thanks