There is so much i dont understand...

Programming, for all ages and all languages.
Post Reply
User avatar
Zacariaz
Member
Member
Posts: 1069
Joined: Tue May 22, 2007 2:36 pm
Contact:

There is so much i dont understand...

Post by Zacariaz »

Code: Select all

class T { 
    unsigned value;
    public:
    T() {value = 0;}
    T(int v) {value = v%13;}
    friend std::ostream& operator <<(std::ostream&, const T&); // i dont understand
};
std::ostream& operator <<(std::ostream& out, const T& data) { // i dont understand
  return out << data.value; 
}
basicly i would like to know what this "ostream" is all about. I have searched the net for guides, tutorial, references, etc. but without much luck, that is i found alot, but nothing i could understand, as seemingly i dont understand even the basic concepts.

Anyway, this code actually works, however i would like to modify it imensely, and in order to do that i need to understand it and af few tutorials about uderdefined datatypes wouldnt be bad either.

I feel bad revealing how little i know, but i need the help.
Anyone?
User avatar
os64dev
Member
Member
Posts: 553
Joined: Sat Jan 27, 2007 3:21 pm
Location: Best, Netherlands

Post by os64dev »

std::ostream is just an object/interface to write to an output stream, for instance console output or in C stdout.

friend std::ostream& operator <<(std::ostream&, const T&);

is the standard method for writing to an ostream (<<). The reason for this prototype(returning a reference to the ostream) is that you can use multple << in a single row/statement. The friend delcaration has to do something with accessibility of the << operator of your class by ostream.

for intstance:

T x, y(1), z(10);

cout << "values: " << x << ", " << y << ", " << z;

which is equivilant to

cout << "values: ";
cout << x;
cout << ", ";
cout << y;
cout << ", ";
cout << z;

would output the string "values: 0, 1, 10" to the console(cout).
Author of COBOS
User avatar
Candy
Member
Member
Posts: 3882
Joined: Tue Oct 17, 2006 11:33 pm
Location: Eindhoven

Post by Candy »

std::ostream is a typedef of a template type - std::basic_ostream<char, char_traits<char> >. There are also similar types for wide character support (unicode) - std::wostream, which is std::basic_ostream<wchar_t, char_traits<wchar_t> >. These are based on std::basic_streambuf<T>'s, which iirc contain the actual reading and writing.

An ostream object is an object that contains knowledge on writing bytes and characters and that delegates all other knowledge to other functions that are declared externally to the object.

You yourself declare such a partial overload to a function that matches all cases in which you pass your type of object and an ostream in the proper order. This is identical to making it a class function of ostream except that you can't edit ostream for that.
Post Reply