home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!pmafire!news.dell.com!swrinde!zaphod.mps.ohio-state.edu!magnus.acs.ohio-state.edu!usenet.ins.cwru.edu!wsu-cs!vela!m.cs.uiuc.edu!sunb10.cs.uiuc.edu!sparc10.cs.uiuc.edu!pjl
- From: pjl@sparc10.cs.uiuc.edu (Paul Lucas)
- Newsgroups: comp.lang.c++
- Subject: Re: operator overloading
- Keywords: pointer usage
- Message-ID: <1992Sep14.152926.5956@sunb10.cs.uiuc.edu>
- Date: 14 Sep 92 15:29:26 GMT
- References: <14513@goanna.cs.rmit.oz.au>
- Sender: news@sunb10.cs.uiuc.edu
- Organization: University of Illinois at Urbana-Champaign
- Lines: 57
-
- In <14513@goanna.cs.rmit.oz.au> djds@goanna.cs.rmit.oz.au (DARYL JOHN D'SOUZA) writes:
-
- >I am seeking clarification of the following note in the Stroustrup text
- >(bottom of page 236):
-
- > "Pointers can not be used because it is not possible to redefine
- > the meaning of an operator when applied to a pointer."
-
- >I tried the following program which seems to compile and run, in contradiction
- >to this statement. I'm sure the problem lies with my misinterpretation of
- >Stroustrup's note, but either way, would someone please elaborate. Here is
- >my C++ program:
-
-
- >//--------program begin
- >#include <iostream.h>
- >#include <iomanip.h>
-
- >class nat { // natural number class
- > int val;
- >public:
- > nat(int i) { val = i; }
- > nat(const nat & n) { val = n.val; }
- > nat & operator = (const nat & n) { val = n.val; return *this; }
- > nat & operator = (int i) { val = i; return *this; }
- > nat operator +(const nat * & r) { return nat(val + r->val); }
- > int access() { return val; }
- >};
-
- >main()
- >{
- > nat i = 10, j = 20, *p = &j;
-
- > i = i + p;
- > cout << i.access() << ' ' << j.access() << ' ' << (*p).access() << endl;
- > i = *p + &i;
- > cout << i.access() << ' ' << j.access() << ' ' << (*p).access() << endl;
- > *p = i + &j;
- > cout << i.access() << ' ' << j.access() << ' ' << (*p).access() << endl;
- >}
-
- *****> So what's the problem? The line:
-
- i = i + p;
-
- is:
- i.operator=( i.operator+( p ) );
-
- that is, you've always got a 'nat' on the LHS of the '+'. The
- operator is being overloaded for that, not its argument.
- Overloaded operators must have at least one class or
- class-reference argument; for members, this argument is
- implicit.
- --
- - Paul J. Lucas University of Illinois
- AT&T Bell Laboratories at Urbana-Champaign
- Naperville, IL pjl@cs.uiuc.edu
-