Re: Why define operator == global and not as a class member?
From: Nick Hounsome (nh002_at_blueyonder.co.uk)
Date: 01/10/04
- Next message: Gerry Quinn: "Re: software protection and licensing question"
- Previous message: Shawn: "beginner help on api and MFC"
- In reply to: Jeff Schwab: "Re: Why define operator == global and not as a class member?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Sat, 10 Jan 2004 11:40:04 -0000
"Jeff Schwab" <jeffplus@comcast.net> wrote in message
news:k5KdnXVo8q9B6GKiRVn-sw@comcast.com...
> Victor Bazarov wrote:
> > "Jeff Schwab" <jeffplus@comcast.net> wrote...
> >
> >>Peter Meier wrote:
> >>
> >>>Hello everybody,
> >>>
> >>>Stroustrup says he prefer's to declare operators, which do not do
> >
> > anything
> >
> >>>on the class itself global. Does anybody know the reason for that?
> >>>Any advantages/disadvantages?
> >>>
> >>>Thank you, Peter
> >>
> >>It makes the syntax similar for built-in and user-defined types.
> >
> >
> > Huh?
> >
> > struct A {
> > bool operator==(A const&) const { return false; }
> > };
> >
> > int main() {
> > A a1, a2;
> > a1 == a2; // Different ???
> > }
>
> You're right, for operators the syntax is identical.
Perhaps you were thinking of the symmetry issue when you want to compare
class to a
builtin- type:
You can write an operator for A() == 42 either as a member or non-member but
42 == A() can only be done with
a non-member.
The usual method is:
struct A
{
A(int x); // conversion from int
int compare(const A&) const; // return positive neagtive or 0 for >,==,<
};
inline bool operator==(const A& a,const A& b) { return a.compare(b) == 0; }
This handles both the cases above by converting the int to an A;
The use of the compare member means that all comparisions are done in one
method and the usual operators
can be trivivially defined as inline non-members that do not need friend
access e.g.
inline bool operator<=(const A& a,const A& b) { return a.compare(b) <= 0; }
etc.
>
> >>Also, IMO, it's a good idea to limit the number of class methods as much
> >>as possible, so that it's relatively easy to monitor accesses to the
> >>class data.
> >
> > Who says that the members have to access class data directly? If you
> > are so inclined to monitor the access, use accessors and monitor.
>
> ...or just don't make things members if they don't need to be.
>
- Next message: Gerry Quinn: "Re: software protection and licensing question"
- Previous message: Shawn: "beginner help on api and MFC"
- In reply to: Jeff Schwab: "Re: Why define operator == global and not as a class member?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|