how do i operator overload <<?

it is said that the it must receive 2 parameters.
1)istream reference(e.g cin)//receives value from cin

2)object reference//to put the values received from cin into the specific object

the error say that the function must take exactly one argument.
so how do I solve this?

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
 #include <iostream>
#include <string>
#include "add.h"
#include "m.h"
#include <fstream>
using namespace std;


class opoverload{
public:
    int x,y;

    istream& operator>>(istream &a,opoverload &obj){
    a>>obj.x;
    return a;
    }

};



int main()
{


}
Last edited on
That operator cannot be a member function. It has to be a standalone function.
Line 13: Put a friend in front of the function:
1
2
3
4
    friend istream& operator>>(istream &a,opoverload &obj){
    a>>obj.x;
    return a;
    }


This actually makes the function standalone (as keskiverto mentioned).
@coder777 Interesting. Usually I've seen the friendship just declared but the definition outside the class' curly braces, but I guess you could implement right then and there too (as long as you realize it's not a member function).

@trumpler Check the function signature -- you should return the stream.

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
47
48
49
50
51
52
#include <iostream>
#include <vector>
#include <sstream>

using namespace std;

class Cell
{
public:
    Cell() {}
    Cell(int x, int y) : x(x), y(y) {} // Useful but unused

    friend ostream& operator<<(ostream& os, const Cell& c)
    {
        os << "(" << c.x << ", " << c.y << ")";
        return os;
    }
    friend istream& operator>>(istream& is, Cell& c)
    {
        is >> c.x >> c.y;
        return is;
    }

private:
    int x;
    int y;
};

int main() 
{
    const char* data_text = R"LITERAL(4 5
12 -3
0 2
19 34
)LITERAL";

    // Imitate file stream
    istringstream iss(data_text);
    
    // Parsing
    vector<Cell> cells;
    Cell tmp;
    while(iss >> tmp)
        cells.emplace_back(tmp);
    
    // Checking data
    cout << "Cells found:\n";
    for (const Cell& c : cells)
        cout << c << '\n';

    return 0;
}

Cells found:
(4, 5)
(12, -3)
(0, 2)
(19, 34)
Topic archived. No new replies allowed.