how should i identify this parameter from a struct inside a function from class?
Nov 12, 2016 at 11:34am UTC
I'm trying to write the set() function and the parameter of it should be length which is part of the struct i tried to call length using the words array/items/price but none of them seemed to work
i need help in identifying my mistakes and fixing my errors
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
#include<iostream>
using namespace std;
struct array
{
int length, *p;
};
class pharmacy
{
private :
array items, price;
int totalsales;
public :
void set(int );
void print();
void calculatetotalsales();
pharmacy(int length=1);
~pharmacy();
pharmacy(const pharmacy&);
};
int main()
{
pharmacy *obj, pObject;
obj = &pObject;
obj -> set(3);
obj -> print();
return 0;
}
void pharmacy::set(int l)
{
length=l;
items= new array[items.length];
cout<<"Enter quantities and price or 3 items: " <<endl;
for (int i=0; i<array.length; i++)
{
cout<<"item#" <<i+1;
cin>>items[i]<<price[i];
}
calculatetotalsales();
}
void pharmacy::calculatetotalsales()
{
totalsales=0;
for (int i=0; i<length; i++)
{
totalsales+=(items[i]*price[i]);
}
}
Last edited on Nov 12, 2016 at 12:13pm UTC
Nov 12, 2016 at 1:49pm UTC
There are two lengths involved, because at line 12 two
array
objects are declared
Function set() might look like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
void pharmacy::set(int l)
{
items.length = l;
items.p = new int [items.length];
price.length = l;
price.p = new int [price.length];
cout<<"Enter quantities and price for " << items.length << " items: " << endl;
for (int i=0; i<items.length; i++)
{
cout << "item#" << i+1;
cin >> items.p[i] >> price.p[i];
}
calculatetotalsales();
}
That seems less than ideal as it is then the programmer's responsibility to make sure that the two separate lengths are always identical. You might want to consider a change to the design, so that just a single length is needed.
Topic archived. No new replies allowed.