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
If I understand well, you want:
p[0]
would hold the quantity of "tissue",p[1]
the quantity of "calendar", etc...About solving your current issue:
Unfortunately your operator overload
int operator-(string &a)
is something that could substract a string value from anA
and return anint
.So in
main()
you should write: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.
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: