Solved

overloaded operator+

Posted on 2003-10-28
18
368 Views
Last Modified: 2013-12-14
I have an assignment that I just can't quite get to work.  Here are the steps
meal class - two fields (entree/calorie count integer) include a constructor that sets meal's feilds with arguments or uses default values when no arguments are provided.  Include an overloaded insertion operator to display meal values and an overloaded extraction operator that prompts the user for entree name and calorie count for a meal
then I need an overloaded operator+() function that will add two or more meal objects(calorie values and creating a summary meal obj to store 'daily total' in entree field
the final step is to have a main program that declares for meal obj breakfast, lunch, dinner and total and include the statement total = breakfast +lunch+dinner and display values for the 4 meal obj.  

I know it's long assignment and I've tried it several ways, but I know I am missing code. I am just not sure what I am missing.  Any help would be appreciated.

#include <iostream.h>
#include <conio.h>
#include <string.h>
#include <fstream.h>

class Meal
{
      friend ostream& operator<<(ostream& out, const Meal &aMeal);
      friend istream& operator>>(istream& in, Meal &aMeal);

      private:
            char *entree;
            double calories;

      public:
            Meal(char ent, int cal);
            double operator+(const Meal &Meal);
};

ostream& operator<<(ostream& out, const Meal &aMeal)
{
      out<< "Meal includes " <<aMeal.entree
            << " for " <<aMeal.calories<<endl;
      return (out);
}

istream& operator>>(istream &in, Meal &aMeal)
{

      cout<< " Enter food name ";
      in>>aMeal.entree;
      cout<< " Enter number of Calories" ;
      in>>aMeal.calories;
      cout<<endl<<" Your Food Intake" <<endl;
      return(in);
}
     


Meal::Meal(char ent, int cal)
{
      *entree = ent;
      calories = cal;
}

  double Meal::operator+(const Meal &aMeal)
  {
      double total;
      total = calories + aMeal.calories;
      return (total);
}


void main()
{

      double total;
      
      Meal Breakfast(' ',200);
    Meal Lunch(' ', 100);
    Meal Dinner(' ', 140);
      cout<<" Enter Breakfast"<<endl;
      cin>>Breakfast;
      cin>>Lunch;
      cin>>Dinner;
      
    cout<<Lunch;
      cout<<Dinner;

      total = Breakfast + Lunch;
      cout<<total<<endl;
      
      getch();
}
0
Comment
Question by:redice
  • 4
  • 4
  • 3
  • +4
18 Comments
 
LVL 86

Accepted Solution

by:
jkr earned 64 total points
ID: 9633937
>>#include <iostream.h>
>>#include <fstream.h>

Please use

#include <iostream>
#include <fstream>

using namespace std;

instead.

>>then I need an overloaded operator+() function that will add two or more meal objects

That would be

Meal& Meal::operator+(const Meal &r) {

  calories += r.calories;

  // concatenate the strings here...
}

As you are mentioning that this is an assignment, it'd defeat the purpose to give you the whole code :o)
0
 
LVL 13

Assisted Solution

by:SteH
SteH earned 62 total points
ID: 9633940
In Meal::Meal (char ent, int cal)
you assign ent to the uninitialized pointer char* entree. Can you use string instead of char*? Then
Meal::Meal (char ent, int cal) changes to
{
 entree += ent;
 calories = cal;
}
Why ist cal int and not double?


operator+ is returning a double not a Meal. Now
Meal a, b, c;
What does
 double total = a + b + c;
mean?
0
 

Author Comment

by:redice
ID: 9633998
thanks for the help.  :)
0
 
LVL 9

Expert Comment

by:_ys_
ID: 9634239
BTW, the canonical format for operator+ is:

const Meal Meal::operator+(const Meal &rhs)
{
    Meal tmp ( this );  // copy construct
    tmp += rhs;         // employ operator+= to do the real work
    return tmp;
}
0
 
LVL 19

Expert Comment

by:mrwad99
ID: 9634253
Yeah, SteH is basically saying that it would be better to use the string class instead of char* for simplicity.  

If you have not been taught about this class yet though:

Meal::Meal(char ent, int cal)
{
    *entree = ent;
    calories = cal;
}

is wrong.  You need to write:

Meal::Meal(char* ent, int cal)
{
    calories = cal;
    entree = new char[strlen(ent)+1];
    strcpy(entree, ent)
}

This allocates the required amount of memory that the entree is then stored in.  Of course, since you are now alloacating memory with new, you must delete it explicitly.

Hence:

Meal::~Meal()
{
    delete [] entree;
}
0
 

Author Comment

by:redice
ID: 9634278
Thanks for the help again.  The class isn't for credit anyway and I'm not a programmer by any means.  Have a great day.
0
 

Author Comment

by:redice
ID: 9634602
operator+ is returning a double not a Meal. Now
Meal a, b, c;
What does
 double total = a + b + c;
mean?

Not sure what it means?
0
 
LVL 9

Assisted Solution

by:_ys_
_ys_ earned 62 total points
ID: 9634703
It means you'll need two operator= variants (or an implicit cast to a double - yuck!!)

double Meal::operator+ (const Meal& r);
double Meal::operator+ (double r);

Against all expectations though.


Better to define an accessor method for the calorie count.

double total = a.cal( ) + b.cal( ) + c.cal( );

This reads better, and is more the norm.
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 2

Assisted Solution

by:xssass
xssass earned 62 total points
ID: 9959291
your overloaded operator+ should return the memory location of the result...

so your function definition should look like this:
 double& Meal::operator+(const Meal &aMeal);

note the & in the return type...

hope this helps.
.K.
0
 
LVL 86

Expert Comment

by:jkr
ID: 9959328
>>your overloaded operator+ should return the memory location of the result...
>>so your function definition should look like this:
>> double& Meal::operator+(const Meal &aMeal);

You'd suggest to return a reference to a local variable?
0
 
LVL 2

Expert Comment

by:xssass
ID: 9959338
indeed
0
 
LVL 86

Expert Comment

by:jkr
ID: 9959368
And you do that without blushing?

int& foo () {

    int i = 4;

    return i;
}
0
 
LVL 2

Expert Comment

by:xssass
ID: 9959461
I once used a similar thing for strings...
my code looked like this:

CString& CString::operator+( const CString& str )
{
    size_t lgth = len + str.len;
    char *t = new char[lgth + 1];
    strcpy( t, s );
    strcat( t, str.s );
    return CString(t);
}

.K.
0
 
LVL 86

Expert Comment

by:jkr
ID: 9959497
You should have received a compiler warning and a memory leak at runtime.
0
 
LVL 2

Expert Comment

by:xssass
ID: 9959765
well I did NOT!

and I am sorry trying to help you!

please excuse me.
.K.
0
 
LVL 9

Expert Comment

by:_ys_
ID: 9962818
I wouldn't call it a memory leak ... it's more of a 'dangling reference'. The local auto variables would already have been cleaned up.

BTW, as a chuckling side-note, the original reply from jkr did have the method signature:

>> Meal& Meal::operator+(const Meal &r)

An oversight I'm sure, but still worth a chuckle.
0
 
LVL 9

Expert Comment

by:tinchos
ID: 10546249
No comment has been added lately, so it's time to clean up this question.
I will leave the following recommendation for this question in the Cleanup topic area:

Split: jkr {http:#9633937} & SteH {http:#9633940} & _ys_ {http:#9634703} & xssass {http:#9959291}

Please leave any comments here within the next four days.
PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!

Tinchos
EE Cleanup Volunteer
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Introduction This article is the first in a series of articles about the C/C++ Visual Studio Express debugger.  It provides a quick start guide in using the debugger. Part 2 focuses on additional topics in breakpoints.  Lastly, Part 3 focuses on th…
Here is a helpful source code for C++ Builder programmers that allows you to manage and manipulate HTML content from C++ code, while also handling HTML events like onclick, onmouseover, ... Some objects defined and used in this source include: …
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
The viewer will learn how to use NetBeans IDE 8.0 for Windows to connect to a MySQL database. Open Services Panel: Create a new connection using New Connection Wizard: Create a test database called eetutorial: Create a new test tabel called ee…

920 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now