Hello everyone,
I’m an intermediate-level C++ programmer grappling with a fairly rudimentary problem. I’m creating a C++ object called FruitCart; FruitCart contains a number of integers categorizing the numbers of individual fruit in the cart. I also need FruitCart to contain accessor functions so other functions can set, retrieve, and print the fruit values. Here’s what I have so far:
--------------------------------------------------------------------------------------
class FruitCart {
public:
// Constructors
FruitCart();
~FruitCart();
// Accessors
void SetApples(int a) {Apples=a;}
int GetApples() {return Apples;}
void PrintApples() {cout<<Apples;}
// Need accessor functions like the above for all kinds of fruit
protected:
int Apples; // Number of Apples in the cart
int Oranges; // Number of Oranges in the cart
int Bananas; // Number of Bananas in the cart
int Plums; // Number of Plums in the cart
// May have nearly 50 kinds of fruit!
};
--------------------------------------------------------------------------------------
The problem I have is that I may have over fifty kinds of fruit in the cart! It would be a big pain to manually write out accessor functions for each kind of fruit.
I’m searching for a more intelligent solution. What I’d like to have is a general accessor function where I pass in the name of the fruit as a string (specifically, as a char * pointer) and leave everything else the same. Put in quasi-psuedocode:
--------------------------------------------------------------------------------------
class FruitCart {
public:
// Constructors
FruitCart();
~FruitCart();
// Accessors
void SetFruit(int a, char * FruitType)
int GetFruit(char * FruitType)
void PrintFruit(char * FruitType)
protected:
int Apples; // Number of Apples in the cart
int Oranges; // Number of Oranges in the cart
int Bananas; // Number of Bananas in the cart
int Plums; // Number of Plums in the cart
};
void FruitCart::SetFruit(int a, char * FruitType)
{ ${FruitType} = a; }
int FruitCart::GetFruit(char * FruitType)
{ return ${FruitType}; }
void FruitCart::PrintFruit(char * FruitType)
{ cout << ${FruitType}; }
--------------------------------------------------------------------------------------
Hopefully this makes sense. I know this would be simple to do in UNIX, so I’m hoping there’s a (relatively) simple way to do this in C++.
Many thanks!
-Pete