0

I'm working on an example from a book, and they give us the prototype (i think its called!) in the class definition and then they want us to define the methods like you would in the cpp file for the class. I'm having trouble understanding mutator methods, specifically in this case with operators. It made more sense when you make them a "Friend" of the class, but in this instance they didnt. I cant seem to figure out how it would behave. Any help would be great!

With the class type being "Mail":

Mail operator=(const Mail& rValue);
Mail operator+(int ounces);

The point of them being that later in main when we create the object mailItem1 we want to add to one of its properties (weight)

mailItem1 = mailItem1 + ADDITIONAL_WEIGHT;

I know you dont necessarily need to see everything but here's the whole class.

class Mail
{
    // Public Interface
public:
    // Class Constructor(s)
    Mail();
    Mail(const char* type, double perOunceCost, int weight);
    Mail(const Mail& other);

    // Class Destructor
    ~Mail()
    { }  // Nothing to do, included for completeness

    // Mutator Methods
    Mail operator=(const Mail& rValue);
    Mail operator+(int ounces);

    // Observer Methods
    double getCost() const;
    friend ostream& operator<<(ostream& stream, const Mail letter);

private:
    // Class "static, const" Constant Values
    static const int TYPE_SIZE = 30;
    static const char FIRST_CLASS[];
    static const double FIXED_COST;
    static const int DEFAULT_WEIGHT = 1;

    // Variable Declarations
    char type[TYPE_SIZE];
    int weight;
    double perOunceCost;
};

I'm confused how that works exactly and would love some help. Thanks!

jacksonSD
  • 677
  • 2
  • 13
  • 27
  • Your `operator =()` should return a reference to `*this`, and your `operator +()` should return a copy. [See **Operator Overloading**](http://stackoverflow.com/questions/4421706/operator-overloading) for more info . – WhozCraig May 28 '14 at 08:48

1 Answers1

0

You should take a look at how the I/O manipulators work. They do what you are trying to do.

Here is an explanation: How do the stream manipulators work?

You are trying to do the same thing with the + operators that the standard library does with <<.

Take a look at the definition of std::endl (no parameters), std::setw (one parameter).

I'd be curious to know what book your are using. This is a very poor example and demonstrates very poor class design.

Community
  • 1
  • 1
user3344003
  • 20,574
  • 3
  • 26
  • 62