operator* as a member function

I am attempting to create a operator* function for a class that converts stones to pounds.

I get the following compile error though :
 
stonewt.h:22:47: error: ‘Stonewt& Stonewt::operator*(Stonewt&, double)’ must take either zero or one argument


the class declaration is:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#ifndef STONEWT_H_
#define STONEWT_H_

#include <iostream>
class Stonewt {
  private:
    enum {Lbs_per_stn = 14}; // pounds per stone
    int stone;
    double pds_left;
    double pounds;

  public:
    Stonewt(double lbs);
    Stonewt(int stn, double lbs) : stone(stn), pds_left(lbs), pounds(stn/Lbs_per_stn) { }
    Stonewt()  { stone = pounds = pds_left = 0; }
    ~Stonewt() { }
    void show_lbs() const;
    void show_stn() const;

    Stonewt& operator*(Stonewt &, const double); // compile error!!!!

    operator int() const {return int (pounds + 0.5); }
    operator double() const {return pounds;}
};

#endif 

definitions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include "stonewt.h"
using std::cout;
#include <iostream>

Stonewt::Stonewt(double lbs) {
  stone = int(lbs) / Lbs_per_stn;
  pds_left = int(lbs) % Lbs_per_stn + lbs - int(lbs);
  pounds = lbs;
}

void Stonewt::show_lbs() const {
  cout << stone << " stone, " << pds_left << " pounds\n";
}

void Stonewt::show_stn() const {
  cout << pounds << " pounds\n";
}

Stonewt& operator *(Stonewt & s, double multiplier) {
  double p = ( (s.stone * Lbs_per_stn) + s.pds_left ) * multipler;
  s.stone = int(p) / Lbs_per_stn;
  pds_left = int(p) % Lbs_per_stn;
  return s;  
}

Can anybody suggest why the compile error?

Last edited on
If it is a MEMBER function, then the left-hand operand LHS in
LHS operator RHS
is the invoking object, so doesn't need to be passed as an argument. You only need one argument (the RHS) and you can refer to stone, not s.stone, for example, in line 20. What you return depends on whether you want to change the invoking object (return *this) or create another Stonewt object: your choice, but multiply usually implies the latter, though.

You could, alternatively, code it as a separate function (usually a 'friend function' if the relevant things you need are private). In this case you would need two arguments for a binary function like *. If your scalar multiplier is on the LHS you don't have much choice but to do this.

See also:
http://www.cplusplus.com/doc/tutorial/templates/
Topic archived. No new replies allowed.