understanding overloaded operators

I've seen these lines of codes before on the internet, they seem to be related to overloaded operators and objects of the library iostream but what do they actually do ?:

1) std::ostream& print(std::ostream &ostr) const;

2) std::ostream& operator<< (std::ostream &ostr, const [class_type] &[class_name]);

3) std::istream& operator>> (std::istream &istr, [class_type] &[class_name]);

4)operator- (const [class_type] &x1, [class_type] &x2)

p.s the [] are not part of the code, they just indicate where the class names and types are placed.
1) looks as a class method, it's not related to operator overloading

2-3) they are used to provide streams operators for some user defined types
eg (use of those overloaded operators):
1
2
3
mytype mt;
cin >> mt;//get someway a value from the user
cout << mt;//display the value of 'mt' 


4) used to do subtraction from two objects of used defined types


eg:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
struct S
{
    int member;
    S(int i):member(i){}
};
S operator- (const S &x1, const S &x2)//Could also be made a member of 'S' in this case
{
    return S(x1.member-x2.member);
}
ostream &operator << (ostream &os, const S &s)
{
    return os << s.member;
}

S a=5, b=3, c = a-b;
cout << c;//should show 2 
Last edited on
Topic archived. No new replies allowed.