Results 1 to 3 of 3

Thread: operator <<

  1. #1

    Thread Starter
    Fanatic Member Wynd's Avatar
    Join Date
    Dec 2000
    Location
    In a bar frequented by colossal death robots
    Posts
    772

    operator <<

    I am trying to make a point class for school, and I get this error: "Error E2080 Point.h 20: 'Point::operator <<(ostream &,const Point &)' must be declared with one parameter". I have no idea what to do, as I had code that worked before like this with the apmatrix class. This is my code (all the relevant parts):

    Code:
    //Point.h
    #include <iostream>
    using namespace std;
    
    class Point
    {
    public:
        ostream& operator <<(ostream&, const Point&);
    private:
        int m_x;
        int m_y;
    };
    
    //Point.cpp
    ostream& Point::operator <<(ostream& os, const Point& p)
    {
        os << "(" << p.m_x << "," << p.m_y << ")";
        return *this; //?
    }
    Alcohol & calculus don't mix.
    Never drink & derive.

  2. #2
    Fanatic Member riis's Avatar
    Join Date
    Nov 2001
    Posts
    551
    Despite my limited C++ knowledge, I'm trying to help you, since operator overloading is actually basic knowledge.
    Try this:
    Code:
    //Point.h
    #include <iostream>
    using namespace std;
    
    class Point
    {
    public:
        friend ostream& operator <<(ostream&, const Point&);
    private:
        int m_x;
        int m_y;
    };
    
    //Point.cpp
    ostream& operator <<(ostream& os, const Point& p)
    {
        return os << "(" << p.m_x << "," << p.m_y << ")";
    }
    Modifications and explanations:
    1) Add the "friend" keyword to the operator<< declaration in your class. The operator<< function needs to access class members.
    2) I've removed the Point:: part from the operator, since it's an operator, and not really a part of the class itself. Because of function overloading the <<-operator knows that it should use your function.
    3) The result of the operator<< function is a stream. You can return this stream immediately.
    os << "(" << p.m_x << "," << p.m_y << ")"; does nothing by itself. The resulting stream object of it is stored nowhere.

    Good luck!

  3. #3

    Thread Starter
    Fanatic Member Wynd's Avatar
    Join Date
    Dec 2000
    Location
    In a bar frequented by colossal death robots
    Posts
    772
    K, thanks
    Alcohol & calculus don't mix.
    Never drink & derive.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width