operator overloading, using char

89 views Asked by At

I want to make stock management program, using operator overload

for example, if one tissue is sold, I want to operate using ' tissue-=1'

I made an array for products inventory P = {1, 2, 3, 4, 5} each for tissue, calendar, fan, book, pen

part of my code(for test) is:

#include<iostream>
#include<string>

using namespace std;

class A{
   public:
      static int p[];
      int operator-(string &a){
         if (strcmp(a, "tissue")==0)
            return p[0]-=1;
         else
            cout<<"error"<<endl;
      }

};

int A::p[]={1,2,3,4,5}

int main(){
   A AA;
   "tissue"-=1;
   return 0;
}

I tried my best as beginner.. I know the codes are very wierd, please tell me anything I missed

1

There are 1 answers

1
Christophe On

If I understand well, you want:

  • AA be a container of objects: p[0] would hold the quantity of "tissue", p[1] the quantity of "calendar", etc...
  • to implement an operator that would decrease the quantity of an object in this container, by using its name.

About solving your current issue:

Unfortunately your operator overload int operator-(string &a) is something that could substract a string value from an A and return an int.

So in main() you should write:

AA - "tissue";  

Improving slightly your approach:

The fact of having a side effect for operator- is very weird. When you write x-1, you don't expect that x is changed, do you ? I'd therefore suggest to improve the readability of your code by using an operator where a side effect is expected.

By the way, I'd also use strings like C++ strings, and not like c-strings.

  A& operator-= (string &a) {
     if (a == "tissue")
        p[0]-=1;    // p[0]-- would be an alternative as well ;-)
     else if (a=="calendar") 
        p[1]-=1; 
     //etc... 
     else
        cout<<"error"<<endl;
     return *this; 
  }

I suppose that your question is only about learning how to use operator overload, and not for wirting production quality code. In this case this approach is fine.

One step further:

In fact what you try to achieve in your own way, is a kind of associative container. Forunately, this already exists in standard C++ with std::map

All your code could be replaced with:

map<string, int> AA; 
AA["tissue"]++; 
AA["calendar"]+=10; 
AA["fan"] = AA["calendar"]*2;
cout << "I have "<<AA["tissue"] <<" tissues in stock"<<endl;