Stuck at ostream operator << overload; need help

How can I overload ostream operator << for next class?
Needed format for output is aaa.bbb (list Prije '.' list Poslije)

1
2
3
4
5
6
7
8
9
10
11
class Dec {
public:

  Dec(double broj);
  Dec(string broj);
private:
  Lista<int> Prije;
  Lista<int> Poslije;

};


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Dec::Dec(double broj){
int a=broj;
while (true)
{
    int b=a%10;
    a=a/10;
    Prije.pushFront(b);
    if (a<1) break;
}
int c=broj;
double trenutni=broj-c;

while (true)
{

    int b=trenutni*10;
    Poslije.pushBack(b);
    trenutni=trenutni*10-b;
    if (trenutni==0) break;
}
}



for example I want to print c in next main:
1
2
3
4
5
6

int main() {
  Realni a(1.5), b(0.8);
  Realni c = a-b;
  cout<<c;
}
Last edited on
Hello pajaPatak,
For operator overloading, have a look at this : https://en.cppreference.com/w/cpp/language/operators
You define the operator like this:
1
2
3
4
5
std::ostream & operator <<(std::ostream &os, const Dec &dec)
{
    // Code to print dec to os
    return os;
}


Since some members of Dec are private, you need to give the operator access to them by making it a friend:
1
2
3
4
5
6
7
8
9
10
class Dec {
public:

  Dec(double broj);
  Dec(string broj);
  friend std::ostream & operator <<(std::ostream &os, const Dec &dec);
private:
  Lista<int> Prije;
  Lista<int> Poslije;
};
Topic archived. No new replies allowed.