Easier way to get values in classes?
Jul 26, 2012 at 9:11pm UTC
Notice the code at the bottom of this (part of the program)
1 2 3
cout << mcsalad.getname() << " " << mcsalad.getage() << " " << mcsalad.getID() << endl;
cout << johnmcsalad.getname() << " " << johnmcsalad.getage() << " " << johnmcsalad.getID() << endl;
is there an easier way to get values rather then writing them out indivudally to rerievte them from the private variables?
the code below is and yes i come up with stupid names when im bored
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
#include <iostream>
using namespace std;
class luckyjohn{
private :
string john;
int age;
double ID;
public :
//constructor call
luckyjohn(){
john = "John Mcsalad" ;
age = 21;
ID = 004;
}
//constructor call
luckyjohn(string x, int xx, double II){
john = x;
age = xx;
ID = II;}
string getname(){
return john;}
int getage(){
return age;}
double getID(){
return ID;}
};
int main()
{
luckyjohn mcsalad;
luckyjohn johnmcsalad("John Nelson" , 21, 557);
cout << mcsalad.getname() << " " << mcsalad.getage() << " " << mcsalad.getID() << endl;
cout << johnmcsalad.getname() << " " << johnmcsalad.getage() << " " << johnmcsalad.getID() << endl;
}
Jul 26, 2012 at 9:22pm UTC
Yes. Overload operator>>.
Jul 26, 2012 at 9:42pm UTC
1 2 3 4
ostream& operator <<(ostream& os, const luckyjohn& lj) { // Second parameter doesn't have to be const, I just like having everything accurate.
os << lj.getname() << ' ' << lj.getage() << ' ' << lj.getID() << endl;
return os;
}
You might have figured it out yourself already, but I felt like helping.
Topic archived. No new replies allowed.