Hi ALL
I was given 2 questions. But have little clue what to do. Please anyone help me.
1) Write a class with an overloaded method used to add numbers.One method should have 2 integer parameters, and the other should take the numbers as a parameter. Use both methods in an example and write the results to the console.
2) Write a class, Item, used to store an item's name and its price. Now write a class PriceList which stores an array of 5 items. Overload the multiplication(*) operator in this class to multiply every item in the price list by the provided amount.
AlanPosted Oct 22, 2007, 4:44 PM
Hi Darren,
The first question doesn't even make sense - I suspect it should read:
1) Write a class with an overloaded method used to add numbers.One method should have 2 integer parameters, and the other should take three numbers as parameters. Use both methods in an example and write the results to the console.
Overloaded methods are methods with the same name but which have different numbers of parameters and/or the parameters are of different types. So, if I tell you that the overloaded methods here are:
public double Add (double x, double y)
{
// code
}
public double Add (double x, double y, double z)
{
// code
}
then, hopefully, you'll be able to finish this question yourself.
The second question doesn't make sense either but I think it means:
2) Write a class, Item, used to store an item's name and its price. Now write a class PriceList which stores an array of 5 items. Overload the multiplication(*) operator in this class to multiply the price of every item in the price list by the provided amount.
Overloading an operator in a class means giving one of the standard C# operators a meaning in relation to objects of that class. Here I think they're expecting you to define the multiplication operator in the PriceList class like this;
class PriceList
{
Item[] items;
public Item[] Items
{
get{ return items;}
}
public PriceList(Item[] items)
{
this.items = items;
}
public static PriceList operator * (PriceList pl, double amount)
{
for(int i= 0; i < 5; i++)
{
Item item = pl.Items[i];
item.Price *= amount;
}
return pl;
}
public static PriceList operator * (double amount, PriceList pl)
{
return pl * amount;
}
}
As multiplication is normally 'commutative' (the result is the same whichever way around the operands are), you'll notice that I've added an overload of the * operator to deal with this which is defined in terms of the other one. Over to you now to finish it off.