CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Apr 2015
    Posts
    2

    Overloading addition and comparing expressions in a while loop

    I have two questions that are related to each other. The first one is about overloading the addition operator.

    I have defined a struct as the following:
    Code:
    #include <iostream>
    #include <string>
    
    struct Sales_data {                                                             
      std:: string bookNo;                                                          
      unsigned units_sold = 0;                                                      
      double revenue = 0.0;                                                         
      // member function for addition operator rules                                
      Sales_data operator + (const Sales_data & data);                              
    };
    I then overloaded the I/O operators so I could print to the screen information related Sales_data.
    Code:
    // overload ostream in order for cout to work                                   
    std::ostream& operator << (std::ostream & out,                                  
                               const Sales_data & cSales_data) {                                                                                           
      out << cSales_data.bookNo << ", " << cSales_data.units_sold << ", "           
          << cSales_data.revenue;                                                   
      return out;                                                                   
    }
    
    // overload istream in order for cin to work                                    
    std::istream& operator >> (std::istream & in, Sales_data & cSales_data) {       
      in >> cSales_data.bookNo >> cSales_data.units_sold >> cSales_data.revenue;    
      return in;                                                                    
    }
    My first issue is with overloading the addition operator. Everyone works correctly except for std::cout << item << std:endl; will no not output the ISBN number only the units_sold and revenue when added together.
    Code:
    // addition operator rules                                                      
    Sales_data Sales_data::operator + (const Sales_data & data2) {                  
      units_sold += data2.units_sold;                                               
      revenue += data2.revenue;                                                     
      return *this;                                                                 
    }
    Now here is the code in its entirety
    Code:
    #include <iostream>
    #include <string>
    
    // Sales_data structure
    struct Sales_data {
      std:: string bookNo;
      unsigned units_sold = 0;
      double revenue = 0.0;
      // member function for addition operator rules
      Sales_data operator + (const Sales_data & data);
    };
    
    // addition operator rules
    Sales_data Sales_data::operator + (const Sales_data & data2) {
      units_sold += data2.units_sold;
      revenue += data2.revenue;
      return *this;
    }
    
    // overload ostream in order for cout to work
    std::ostream& operator << (std::ostream & out,
                               const Sales_data & cSales_data) {
      out << cSales_data.bookNo << ", " << cSales_data.units_sold << ", "
          << cSales_data.revenue;
      return out;
    }
    
    // overload istream in order for cin to work
    std::istream& operator >> (std::istream & in, Sales_data & cSales_data) {
      in >> cSales_data.bookNo >> cSales_data.units_sold >> cSales_data.revenue;
      return in;
    }
    
    int main(int argc, char *argv[]) {
      Sales_data item, total;  // declare item,total as a Sales_data type
      // prompt the user for the information to enter
      std::cout << "Enter ISBN, units sold, and revenue:" << std::endl;
      while (std::cin >> item) {
        // allow the user to enter in as many items as they deem necessary
        // what to put here??
        total = total + item;  // add each new item to the total
      }
      std::cout << "The total units sold and revenue is " << total << std::endl;
      return 0;
    }
    1. After total = total + item;, I would like to print the total for this particular ISBN. However, I only get: blank, total units, total revenue where blank is where the ISBN would go but doesn't print after addition.

    My second question has to do with comparing the ISBN's of the books entered during the while loop.
    1. I would like to do something like
      Code:
      if (item_i.bookNo == item_i+1.bookNo) {
        total = total + item;
      } else {
        std::cerr << "Books entered must have the same ISBNs" << std::endl;
      }

    Unfortunately, I cannot figure out how to set up a comparison of the bookNos. If I used #include <casset> in the overload + rule, it will immediately exit since I have no way to compare the ISBNs.

  2. #2
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: Overloading addition and comparing expressions in a while loop

    It looks like you are trying to overload operator+ when you should be overloading operator+= instead:
    Code:
    Sales_data& Sales_data::operator+=(const Sales_data& other) {
        if (bookNo != other.bookNo) {
            throw std::invalid_argument("Books entered must have the same ISBNs");
        }
    
        units_sold += other.units_sold;
        revenue += other.revenue;
        return *this;
    }
    Once you have done this, you can overload operator+ as a non-member function:
    Code:
    Sales_data operator+(Sales_data lhs, const Sales_data& rhs) {
        return lhs += rhs;
    }
    Quote Originally Posted by dwsmith
    My first issue is with overloading the addition operator. Everyone works correctly except for std::cout << item << std:endl; will no not output the ISBN number only the units_sold and revenue when added together.
    This does not sound like a problem with operator+ since operator+ should not be expected to deal with the ISBN. Rather, this is probably a problem with the construction of the Sales_data object, i.e., you did not create it or otherwise populate it with the ISBN.

    Quote Originally Posted by dwsmith
    My second question has to do with comparing the ISBN's of the books entered during the while loop.
    (...)
    Unfortunately, I cannot figure out how to set up a comparison of the bookNos. If I used #include <casset> in the overload + rule, it will immediately exit since I have no way to compare the ISBNs.
    I presume that by <casset> you mean <cassert>. That would definitely be wrong since assertions are meant to check pre-conditions/post-conditions and other assumptions, not to implement actual logic. There are two possible approaches that come to mind:
    • If you expect the data to be entered such that entries with the same ISBN are always consecutive, then it would be sufficient to store the Sales_data objects in a std::vector and access the last element of the vector as the current Sales_data object. If the newest entry has the same ISBN as the current Sales_data object, you add it to the current Sales_data object. Otherwise, you create a new Sales_data object with the entry and append it to the vector.
    • If the ISBNs are not necessarily consecutive, then you could use a std::map or std::unordered_map to map ISBNs to Sales_data objects. This way, you attempt to find an element with the newest entry's ISBN in the map. If it is found, you add it to that element, otherwise you create a new Sales_data object with the entry and insert it into the map.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  3. #3
    Join Date
    Apr 2015
    Posts
    2

    Re: Overloading addition and comparing expressions in a while loop

    I dont think I understand correctly, what I have tried from your reply is:
    Code:
    // Sales_data structure                                                         
    struct Sales_data {                                                             
      std:: string bookNo;                                                          
      unsigned units_sold = 0;                                                      
      double revenue = 0.0;                                                         
      // member function for addition operator rules                                
      Sales_data operator + (const Sales_data & data);  // should this be commented out?                              
    };
    
    // += operator rules                                                            
    Sales_data & Sales_data::operator += (const Sales_data & data2) {               
      if (bookNo != data2.bookNo) {                                                 
        throw std::invalid_argument("Books entered must have the same ISBNs");      
      }                                                                             
      units_sold += data2.units_sold;                                               
      revenue += data2.revenue;                                                     
      return *this;                                                                 
    }
    
    Sales_data operator + (Sales_data lhs, const Sales_data & rhs) {                
      return lhs += rhs;                                                            
    }
    I ask because I have tried this with Sales_data operator + (const Sales_data & data); and commented out but both produce the following error:
    Code:
    error: no ‘Sales_data& Sales_data::operator+=(const
    Sales_data&)’ member function declared in class ‘Sales_data’
     Sales_data & Sales_data::operator += (const Sales_data & data2) {
                                                                   ^
    In function ‘Sales_data operator+(Sales_data, const
    Sales_data&)’:
    error: no match for ‘operator+=’ (operand types are
    ‘Sales_data’ and ‘const Sales_data’)
       return lhs += rhs;
    I am sorry if this is a trivial question, but I am learning C++ on my own from C++ Primer 5th Ed; I am only on Ch 2.

  4. #4
    Join Date
    Aug 2000
    Location
    New York, NY, USA
    Posts
    5,656

    Re: Overloading addition and comparing expressions in a while loop

    1. As laserlight suggested, your total variable is default-constructed, and it's bookNo filed is empty as it was never initialized.
    2. You are forcing your users to enter the same ISBN (very long number, IIRC) over and over. Instead, you should get ISBN, then prompt (in a loop) for other data.
    Vlad - MS MVP [2007 - 2012] - www.FeinSoftware.com
    Convenience and productivity tools for Microsoft Visual Studio:
    FeinWindows - replacement windows manager for Visual Studio, and more...

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured