Why does the overstream insert / extract function require the ostream / istream argument?

Consider the following code with overloaded insert and extract operators.

#include <iostream>

using namespace std;

class CTest
{
    string d_name;
public:
    friend ostream & operator<<(ostream & out, CTest & test);
    friend istream & operator>>(istream & in, CTest & test);
};

ostream & operator<<(ostream & out, CTest & test)
{
    out << "Name: " << test.d_name;
    return out;
}

istream & operator>>(istream & in, CTest & test)
{
    cout << "Enter your name: ";
    string name;
    if(in >> name)
        test.d_name = name;

    return in;
}

int main()
{
    CTest test;
    cin >> test;   // (1)
    cout << test;  // (2)
}

Following this question, what is the meaning of the arguments ostream, out and istream and in? Since we can only see one argument (cin → test or cout <test), where in the caller are there ostream / istream links passed to (1) or (2)?

+4
source share
3 answers

Since in cin >> testand cout << testthere are two arguments.

cinhas type istream.

couthas type ostream.

These types may be different than coutand cin. For example, they may be cerr, clogor stringstream.

, , - .

+2
cin >> test;

- cin std::istream, - CTest.

>>

friend istream& operator >> (istream& s, Your class &);

, .

0

To better understand where the two arguments came from, you can rewrite the main () function as follows:

int main()
{
    CTest test;
    operator>>(std::cin, test);
    operator<<(std::cout, test);
}
0
source

Source: https://habr.com/ru/post/1687411/


All Articles