I am making a class Customer
that has the following data members and properties:
private string customerName;
private double[] totalPurchasesLastThreeDays; //array of 3 elements that will hold the totals of how much the customer purchased for the past three days i.e. element[0] = 100, element[1] = 50, element[2] = 250
public string CustomerName
{
get { return customerName; }
set { customerName = value; }
}
public double[] TotalPurchasesLastThreeDays
{
?
}
How do I define the get and set for the array data member?
Array provides methods of the form setFoo() and getFoo() for setting and getting components of any primitive type. For example, the component of an int array may be set with Array. setInt(Object array, int index, int value) and may be retrieved with Array. getInt(Object array, int index) .
An array is a data structure that contains a group of elements. Typically these elements are all of the same data type, such as an integer or string. Arrays are commonly used in computer programs to organize data so that a related set of values can be easily sorted or searched.
Here is what you can do: #include <algorithm> int array [] = {1,3,34,5,6}; int newarr [] = {34,2,4,5,6}; std::copy(newarr, newarr + 5, array); However, in C++0x, you can do this: std::vector<int> array = {1,3,34,5,6}; array = {34,2,4,5,6};
Do you want an indexer?
public double this[int i] {
get { return totalPurchasesLastThreeDays[i]; }
set { totalPurchasesLastThreeDays[i] = value; }
}
Because otherwise the question sounds a little weird, given that you already implemented a property in your code and are obviously capable of doing so.
You can use an auto-property:
public class Customer
{
public string CustomerName { get; set; }
public double[] TotalPurchasesLastThreeDays { get; set; }
}
Or if you want:
public class Customer
{
private double[] totalPurchasesLastThreeDays;
public string CustomerName { get; set; }
public double[] TotalPurchasesLastThreeDays
{
get
{
return totalPurchasesLastThreeDays;
}
set
{
totalPurchasesLastThreeDays = value;
}
}
}
And then in the constructor, you can set some default values:
public Customer()
{
totalPurchasesLastThreeDays = new double[] { 100, 50, 250 };
}
You might be asking yourself this question because you think that assigning to your array is different than a regular variable?
In that case, you have to realize that when you call TotalPurchasesLastThreeDays[3] = 14.0
you are actually using the getter and not the setter. The setter is used to change the array itself and not the values it contains. So coding the getter and setter isn't any different with an array than with any other variable type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With