I have achieved to overload operator <<, I have found out that It can not be a member of the function if I want to overload <<, so at the moment I have had to make public every member to make the variable accesible...but I would like to keep them private...I have read that I have to do something like a passthrough...I gues it must be a member function who is able to take the variable and send them to the operator but I dont know how...at the momento I have got this..
operator<< cannot be a member function of the class as the lefthand operand must be an ostream&, and that doesn't work for class members (the class is always the lefthand operand.)
@Winsu
As Yanson gave as an altenative, you can make the operator<< overload a friend of you class, then you can avoid making data members public.
#include <iostream>
usingnamespace std;
// simplified class
class integer {
private:
int value; // private!!
public:
integer(int v = 0) : value(v) {}
// make operator<< overload a friend so can access private members
friend ostream& operator<<(ostream &os, const integer& x);
};
// should return ostream& ref (to support operator chaining,
// like cout << i << j << k << "\n")
ostream& operator<<(ostream &os, const integer& x){
os << x.value; // write integer private data to os, not cout!!
return os; // and return os
}
int main(){
integer first(3);
integer second(2);
integer third(1);
integer fourth; // default to zero
// chained calls
cout << first << ", " << second << ", " << third << ", " << fourth << "\n";
return 0;
}
or you could provide a public method which writes to a stream, if this might be useful in other situations:
I undertand how both code work completely, but I have question...., for example with operator + overloaded when you do this a + b...It's kind of equivalent to a.operator+(b).Knowking this I understand why operator << can not be a member...but when I think in the call for operator << when It's overloaded, it must be called with an ostream object...so thinking that a is an object of integer ( integer a) the equivalent of ...cout<<a, could be something like this.. os.operator<<(a)...so operator << always use os as a member os ostream and any type too....more than a question It has been an explanationof I understand and If there is something that I am missing..
But trying to do it like your second suggestions I'am having an issue,the compiler launch me an errot which says: initializing argument 1 of 'std::ostream& operator<<(std::ostream, const integer&)' multiplicated by 3 because of 3 << in main...I dont knwo if doing that I have to change somethin in my constructor...this is my code...I paste everything..