home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!cis.ohio-state.edu!pacific.mps.ohio-state.edu!linac!uwm.edu!cs.utexas.edu!sdd.hp.com!wupost!gumby!destroyer!ubc-cs!mala.bc.ca!epp
- From: epp@mala.bc.ca (Lorne Epp)
- Newsgroups: comp.lang.c++
- Subject: Re: HELP with overloading binary operator...
- Message-ID: <1992Jul28.142121.606@mala.bc.ca>
- Date: 28 Jul 92 14:21:21 -0700
- References: <28JUL199210114546@ariel.lerc.nasa.gov>
- Organization: Malaspina College
- Lines: 74
-
- In article <28JUL199210114546@ariel.lerc.nasa.gov>, smneyln@ariel.lerc.nasa.gov (Michael Neylon) writes:
- > I have the following class...
- >
- > class ARRAYBASE {
- > private: float matrix[MAXSIZE][MAXSIZE];
- > public: int xsize, ysize;
- > ARRAYBASE(int x, int y) {xsize=x+1;ysize=y+!;};
- > // put + get handlers
- > // overloaded operator= which is fine
- > // Inverse() function, taken from _Num. Rec. in C_
- > ARRAYBASE ARRAYBASE::operator*(ARRAYBASE array1, ARRAYBASE array2)
- > {
- > //fill the array using matrix multiplication
- > //fill in matrix[][] and xsize, and ysize vars
- > return *this;
- > };
- > };
- >
- > (obviously, this defines arrays with a base as 1 (a[1..6][1..6]))
- > However, when i compile, i get...
- > ARRAYBASE::operator*() must take only 0 or 1 arguments
-
- Since you have declared operator* as a member of arraybase, it has an
- implied argument, the <this> pointer, which is the left operand of the
- expression A2*A3. This means that an overloaded binary operator that
- is implemented as a member function should have only one explicit
- argument. There are two things you can do:
-
- //
- // Member function - implied argument is ARRAYBASE *this
- //
- ARRAYBASE ARRAYBASE::operator*(const ARRAYBASE &array1 )
- {
- ARRAYBASE array;
- /* Code to multiply *this by array1, putting
- result in array */
- return array;
- };
-
- or...
- //
- // Friend function - there is no implied argument, so both
- // arguments appear in the parameter list.
- //
- friend
- ARRAYBASE ARRAYBASE::operator*(const ARRAYBASE &array1,
- const ARRAYBASE &array2 )
- {
- ARRAYBASE array;
- /* Code to multiply array1 by array2, putting
- result in array */
- return array;
- };
-
- (Note that the arguments are now declared "const ARRAYBASE &" instead
- of "ARRAYBASE" - this is not required, but it saves memory and
- copy constructor calls.)
-
- > huh? this is the same format that I can find in several C++ books for
- > overloaded binary operators. Whats wrong?!
- >
- Your code resembles the format for overloaded binary operators with
- side effects, such as
-
- const FOO &FOO::operator+=( const FOO &foo ) // Only one argument
- { /* add foo to *this leaving result in *this */
- return *this;
- }
- Use this form when you want side effects. I don't think you want them
- in the example you gave, though.
-
-
- Lorne Epp
- epp@mala.bc.ca
-