Archived

This topic is now archived and is closed to further replies.

heff

C++ question about "friends"

Recommended Posts

I''m trying to declare a friend function inside of a class and define it outside the class. My code basically looks like this: class Transition { . . friend bool operator<(Transition lhs, Transition rhs); . . }; bool operator<(Transition lhs, Transition rhs) { . . } MSVC++ gives me an error saying that (<) doesn''t have access to Transition''s private data. I don''t get the error if I define the function inside of the class "in-line" style. I would rather define it outside of the class if possible, cause it''s several lines of code. Every C++ book I have tells me that I can define it outside. Is this a bug in MSVC++? chris

Share this post


Link to post
Share on other sites
Why not do:

class classname
{
...
bool operator<(classname rhs);
...
};

bool classname::operator<(classname rhs)
{
...
}

the "lhs" is implied in the "this" pointer

{if(this->data < rhs.data) return true; return false; }

Edited by - Assassin on February 17, 2002 4:48:16 PM

Share this post


Link to post
Share on other sites
thanks for the help Assassin, anyway, apparently it is a bug, I just didn''t have the patch installed at the time. After I installed the service pack it compiled.

I''m trying to use my class in the STL set container, which requires you to declare the "less-than" operator. I''m not sure if I can use only the one argument version that you suggested.

chris

Share this post


Link to post
Share on other sites
quote:
Original post by Assassin
Why not do:

class classname
{
...
bool operator<(classname rhs);
...
};

bool classname::operator<(classname rhs)
{
...
}

Because this restricts the ability to use implicit conversions for the left-hand side of the expression. (Sometimes this is what you want, but very rarely.)


[ MSVC Fixes | STL | SDL | Game AI | Sockets | C++ Faq Lite | Boost ]

Share this post


Link to post
Share on other sites
Suppose the implicit this instance was declared constant - you now need to define/declare two flavors of operator<, one const, one non-const.

Unless Transition is a very small class, pass it by reference. And declare the actual function to be inline.
  
friend bool operator<(const Transition& lhs, const Transition& rhs);

Share this post


Link to post
Share on other sites