A problem with overloading << (compiler = djgpp)

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Tatu Portin

    #1

    A problem with overloading << (compiler = djgpp)

    1: #include <iostream>
    2:
    3: typedef struct {
    4: double r;
    5: double i;
    6: } complex;
    ..
    ..
    ..
    24: ostream & operator<< (ostream &str, const complex &a)
    25: {
    26: s << "(" << a.r << " + i" << a.i ")";
    27: return s;
    28: }

    when compiled with gcc:
    [color=blue]
    >gcc complex.cc[/color]
    complex.cc:24: syntax error before `&' token

    I think this error has something to do with that 'ostream'. I have #included
    <iostream>, so that should not cause this?
  • John Harrison

    #2
    Re: A problem with overloading &lt;&lt; (compiler = djgpp)


    "Tatu Portin" <axel86@mbnet.f i> wrote in message
    news:3yR7d.96$X 94.42@read3.ine t.fi...[color=blue]
    > 1: #include <iostream>
    > 2:
    > 3: typedef struct {
    > 4: double r;
    > 5: double i;
    > 6: } complex;[/color]

    That is C style code, its not wrong but in C++ we prefer

    struct complex {
    double r;
    double i;
    };
    [color=blue]
    > .
    > .
    > .
    > 24: ostream & operator<< (ostream &str, const complex &a)
    > 25: {
    > 26: s << "(" << a.r << " + i" << a.i ")";
    > 27: return s;
    > 28: }
    >
    > when compiled with gcc:
    >[color=green]
    > >gcc complex.cc[/color]
    > complex.cc:24: syntax error before `&' token
    >
    > I think this error has something to do with that 'ostream'. I have
    > #included <iostream>, so that should not cause this?[/color]

    You are forgetting that ostream is in the std namespace.

    std::ostream & operator<< (std::ostream &str, const complex &a)

    Also look at

    using std::ostream;

    or

    using namespace std;

    John


    Comment

    • Tatu Portin

      #3
      Re: A problem with overloading &lt;&lt; (compiler = djgpp)

      Did help! Thank you, John!

      Comment

      Working...