CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Dec 2002
    Location
    israel
    Posts
    23

    problem with operator overloading!

    i wanted to do this :
    class vector3d {
    private :
    int x,y,z;
    public :
    int operator==(vector3d,vector3d);
    friend int operator==(vector3d,float);
    friend int operator==(float,vector3d);
    };
    after this declareration i have made the 3 functions,
    but when i try to do :

    vector3d v1,v2;
    float f1=10;
    cout << f1==v2;
    i get an error!
    why?
    thnaks in advance
    peleg

  2. #2
    Join Date
    Apr 1999
    Location
    Altrincham, England
    Posts
    4,470
    operator== should return bool, not int.

    Only the variant with float as the left-hand operand needs to be declared as a free function, the other two can be normal member functions.

    Binary operators, when implemented as member functions, take one argument.
    Code:
    class vector3d
    {
    private :
        int x,y,z;
    public :
        bool operator==(const vector3d&) const;
        bool operator==(float) const;
    };
    
    bool operator==(float f, const vector3d& v)
    {
        return v == f;
    }
    Correct is better than fast. Simple is better than complex. Clear is better than cute. Safe is better than insecure.
    --
    Sutter and Alexandrescu, C++ Coding Standards

    Programs must be written for people to read, and only incidentally for machines to execute.

    --
    Harold Abelson and Gerald Jay Sussman

    The cheapest, fastest and most reliable components of a computer system are those that aren't there.
    -- Gordon Bell


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

Featured