overloading.
What should fix so run my program?
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
|
#include <iostream>
using namespace std;
class Food
{
private:
int water;
int chicken;
public:
Food(int w,int c)
{
water=w;
chicken=c;
}
friend Food operator+(const Food &c1, const Food &c2);
int GetCents()
{
cout<<"I have "<<water<<" glass of water\nAnd "<<chicken<<"chickens";
}
};
// note: this function is not a member function!
Food operator+(const Food &c1, const Food &c2)
{
Food temp;
temp.water=c1.water + c2.water;
temp.chicken=c1.chicken + c2.chicken;
return temp;
}
int main()
{
Food ce1(6,3),ce2(8,4),cCentsSum;
cCentsSum = ce1 + ce2;
cCentsSum.GetCents();
return 0;
}
|
Thanks
you need a constructor without parameter:
1 2 3 4 5
|
Food()
{
water=0;
chicken=0;
}
|
or default parameter:
1 2 3 4 5
|
Food(int w = 0,int c = 0)
{
water=w;
chicken=c;
}
|
YOU ARE FUCKING PERFECT.THAAAAAAAAAAAANKS.
That was fantastic explanation.
But can exaplain me why i need put as first value the zero?
It was an example. You can use whatever value you prefer.
yes,but why i must put a value?
Or
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
Food operator+(const Food &c1, const Food &c2)
{
return Food(
c1.water+c2.water,
c1.chicken+c2.chicken,
);
}
int main(){
Food ce1(6,3),ce2(8,4);
Food cCentsSum = ce1 + ce2;
cCentsSum.GetCents();
return 0;
}
|
You were trying to construct a Food object without providing its values.
That's like going to the electronic store and ask for an integrated circuit.
Last edited on
Topic archived. No new replies allowed.