Operator cin overload
Mar 10, 2012 at 4:51pm UTC
If my variables are public the operator cin works no problem,but if they are private it doesnt work.I try to fix the problem with set functions ,but still doesnt work
Thanks
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
#include <iostream>
using namespace std;
class MyClass
{
public :
MyClass() : varI(0),varF(0) {}
MyClass(int i,float f): varI(i),varF(f) {}
int getVarI() { return varI; }
float getVarF() { return varF; }
void setVarI(int i) {varI=i;}
void setVarF(float f) {varF=f;}
private :
int varI;
float varF;
};
ostream& operator <<(ostream& out,MyClass & o)
{
out<<o.getVarI()<<"-" <<o.getVarF()<<endl;
return out;
}
istream& operator >>(istream &input,MyClass &o)
{
input>>o.setVarI(o.varI);
input>>o.setVarF(o.varF);
return input;
}
int main()
{
MyClass o1(2,33.3);
cout<<o1;
MyClass o2;
cout<<"Enter int and float: " ;
cin>>o2;
cout<<"The entered numbers are: " ;
cout<<o2;
}
Mar 10, 2012 at 5:06pm UTC
i don't really know about this too, but as far as i know, the overloaded functions is not your class' member function, it should be:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
class MyClass
{
public :
MyClass() : varI(0),varF(0) {}
MyClass(int i,float f): varI(i),varF(f) {}
int getVarI() { return varI; }
float getVarF() { return varF; }
void setVarI(int i) {varI=i;}
void setVarF(float f) {varF=f;}
friend istream& operator >> (istream & input, MyClass& o);
private :
int varI;
float varF;
};
Last edited on Mar 10, 2012 at 5:07pm UTC
Mar 10, 2012 at 5:21pm UTC
Thanks,with friend and accessint the variables directly work
Is there way to set the variables with set functions
Mar 14, 2012 at 2:31pm UTC
what do you mean set the variable? i thought, by making a member function, you already know how to use them...
1 2 3 4
//define outside the class
void MyClass::setVarI(int i) {
varI = i;
}
hope helps...
Mar 14, 2012 at 7:55pm UTC
Thanks,with friend and accessint the variables directly work
Is there way to set the variables with set functions
1 2 3 4 5 6 7 8 9
istream& operator >>(istream &input,MyClass &o)
{
int i ;
float f ;
input >> i >> f;
o.setVarI(i) ;
o.setVar(f) ;
return input;
}
Last edited on Mar 14, 2012 at 7:56pm UTC
Mar 14, 2012 at 10:07pm UTC
cin is not an operator, it's an object of class istream. You would need to overload the >> operator
Topic archived. No new replies allowed.